Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expanding variables Bash Scripting

I have two variables in bash that complete the name of another one, and I want to expand it but don't know how to do it I have:

echo $sala
a
echo $i
10

and I want to expand ${a10} in this form ${$sala$i} but apparently the {} scape the $ signs.

like image 397
Josepas Avatar asked Feb 25 '26 11:02

Josepas


1 Answers

There are a few ways, with different advantages and disadvantages. The safest way is to save the complete parameter name in a single parameter, and then use indirection to expand it:

tmp="$sala$i"     # sets $tmp to 'a10'
echo "${!tmp}"    # prints the parameter named by $tmp, namely $a10

A slightly simpler way is a command like this:

eval echo \${$sala$i}

which will run eval with the arguments echo and ${a10}, and therefore run echo ${a10}. This way is less safe in general — its behavior depends a bit more chaotically on the values of the parameters — but it doesn't require a temporary variable.

like image 114
ruakh Avatar answered Feb 27 '26 03:02

ruakh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!