0

This question already has an answer here:

In bash, I have defined

chg_Li=3
chg_Na=9

Now I want to call $chg_$i where i is in a for loop, looping over Li and Na.

What is the correct syntax to call $chg_$i?

marked as duplicate by don_crissti, αғsнιη, Jeff Schaller, peterh, jasonwryan Oct 3 '17 at 23:05

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

You can use eval or indirection:

eval echo \$chg_$i

or

varname=$chg_$i
echo ${!varname}
  • 1
    Preferably indirection. When using eval, your first thought should be "If I'm using eval, I probably need to rethink my approach" in nearly all cases. – DopeGhoti Oct 3 '17 at 22:34
0

As was mentioned, you can use indirection for this:

$ chg_Li=3
$ chg_Na=9
$ post_fix=(Li Na)
$ for j in ${post_fix[@]}; do chg="chg_$j"; echo "${!chg}"; done;
3
9

Not the answer you're looking for? Browse other questions tagged or ask your own question.