Michael
Michael

Reputation: 644

Bash - Print value of variable in array

I want to do something like this

A='123'
B='143'
C='999'

declare -a arr=(A B C)

for i in "{$arr[@]}"
do
     echo "@i" "$i" 
done

Which should give me the output of

A 123
B 143
C 999

But instead I receive the variable names, not the value in the output (I just see "A @i" in the output...

Upvotes: 1

Views: 239

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74645

If you want to store the variable names in the loop, rather than copy their values, then you can use the following:

for i in "${arr[@]}"; do
    echo "${!i}"
done

This means that the value of i is taken as a name of a variable, so you end up echoing $A, $B and $C in the loop.

Of course, this means that you can print the variable name at the same time, e.g. by using:

echo "$i: ${!i}"

It's not exactly the same, but you may also be interested in using an associative array:

declare -A assoc_arr=( [A]='123' [B]='143' [C]='999' )

for key in "${!assoc_arr[@]}"; do
    echo "$key: ${assoc_arr[$key]}"
done

Upvotes: 2

Cyrus
Cyrus

Reputation: 88654

I suggest to add $:

declare -a arr=("$A" "$B" "$C")

Upvotes: 1

Related Questions