Reputation: 644
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
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