Dynamic variable names in Bash

后端 未结 14 1999
清酒与你
清酒与你 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:26

    As per BashFAQ/006, you can use read with here string syntax for assigning indirect variables:

    function grep_search() {
      read "$1" <<<$(ls | tail -1);
    }
    

    Usage:

    $ grep_search open_box
    $ echo $open_box
    stack-overflow.txt
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题