1

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...

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent, this is exactly what I was looking for.
@Michael you might also be interested in using an associative array - see my edit.
1

I suggest to add $:

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

1 Comment

Yes, I understand that is an alternative for the example but in reality I would like to able to output both the variable name and the value. Is that possible?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.