Dynamic variable names in Bash

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

    Use an associative array, with command names as keys.

    # Requires bash 4, though
    declare -A magic_variable=()
    
    function grep_search() {
        magic_variable[$1]=$( ls | tail -1 )
        echo ${magic_variable[$1]}
    }
    

    If you can't use associative arrays (e.g., you must support bash 3), you can use declare to create dynamic variable names:

    declare "magic_variable_$1=$(ls | tail -1)"
    

    and use indirect parameter expansion to access the value.

    var="magic_variable_$1"
    echo "${!var}"
    

    See BashFAQ: Indirection - Evaluating indirect/reference variables.

提交回复
热议问题