4

I am trying to do something like below:

for a in apple orange grape; do
    ${!a}="blah"
done
echo $apple
blah

Possible?

2 Answers 2

5

Use declare.

for a in apple orange grape; do
    declare "$a=blah"
done
Sign up to request clarification or add additional context in comments.

2 Comments

+1; ingenious solution; alternative form that may make what's going on a little clearer: declare $a='blah' - there's no need to or point in double-quoting $a, because declare will not apply expansions to the left side (and anything that truly needs quoting wouldn't work as a variable name anyway).
Or alternatively to declare: printf -v $a "%s" "blah"
4

I wonder if you might want to use associative arrays instead:

declare -A myarray
for a in apple orange grape; do
    myarray[$a]="blah"
done
echo ${myarray[apple]}

Note associative arrays require version 4.0 or greater.

Comments

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.