Dynamic variable names in Bash

后端 未结 14 2023
清酒与你
清酒与你 2020-11-21 05:38

I am confused about a bash script.

I have the following code:

function grep_search() {
    magic_way_to_define_magic_variable_$1=`ls | tail -1`
    e         


        
14条回答
  •  执念已碎
    2020-11-21 06:31

    Even though it's an old question, I still had some hard time with fetching dynamic variables names, while avoiding the eval (evil) command.

    Solved it with declare -n which creates a reference to a dynamic value, this is especially useful in CI/CD processes, where the required secret names of the CI/CD service are not known until runtime. Here's how:

    # Bash v4.3+
    # -----------------------------------------------------------
    # Secerts in CI/CD service, injected as environment variables
    # AWS_ACCESS_KEY_ID_DEV, AWS_SECRET_ACCESS_KEY_DEV
    # AWS_ACCESS_KEY_ID_STG, AWS_SECRET_ACCESS_KEY_STG
    # -----------------------------------------------------------
    # Environment variables injected by CI/CD service
    # BRANCH_NAME="DEV"
    # -----------------------------------------------------------
    declare -n _AWS_ACCESS_KEY_ID_REF=AWS_ACCESS_KEY_ID_${BRANCH_NAME}
    declare -n _AWS_SECRET_ACCESS_KEY_REF=AWS_SECRET_ACCESS_KEY_${BRANCH_NAME}
    
    export AWS_ACCESS_KEY_ID=${_AWS_ACCESS_KEY_ID_REF}
    export AWS_SECRET_ACCESS_KEY=${_AWS_SECRET_ACCESS_KEY_REF}
    
    echo $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY
    aws s3 ls
    

提交回复
热议问题