Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set new variable with name of string from existing variable

Tags:

bash

I am trying to do something like below:

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

Possible?

like image 467
cashman04 Avatar asked Jan 11 '23 18:01

cashman04


2 Answers

Use declare.

for a in apple orange grape; do
    declare "$a=blah"
done
like image 152
chepner Avatar answered Jan 19 '23 10:01

chepner


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 bash version 4.0 or greater.

like image 28
Digital Trauma Avatar answered Jan 19 '23 11:01

Digital Trauma