Search code examples
bashvariablesevalassociative-arrayvariable-names

Examine Bash variables with dynamic names


I'm trying to read from Bash variables for which I know name suffixes, but I want to iterate through the prefixes.

I give an example below:

var1_name="variable1"
var1_size="2"
var2_name="variable2"
var2_size="3"
vars=(var1 var2)

for v in "${vars[@]}"
do
    echo $v_name
    echo $v_size
done

and I'd want the output to look like follows:

variable1
2
variable2
3

Is there any to do this with Bash? I have tried with eval and associative arrays, but I still can't find a way to examine an already defined variable.


Solution

  • Below works for me. You need to construct the variable first and then evaluate it using exclamation.

    var1_name="variable1"
    var1_size="2"
    var2_name="variable2"
    var2_size="3"
    vars=("var1" "var2")
    
    for v in "${vars[@]}"
    do
        name=${v}_name
        size=${v}_size
        echo ${!name}
        echo ${!size}
    done
    

    O/P

    variable1
    2
    variable2
    3