Set a new variable with the name of the string from the existing variable

I am trying to do something like below:

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

Possible?

+4
source share
2 answers

Use declare.

for a in apple orange grape; do
    declare "$a=blah"
done
+5
source

I wonder if you can associative arrays instead :

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

Note that associative arrays require version 4.0 or higher.

+4
source

Source: https://habr.com/ru/post/1537776/


All Articles