Josepas
Josepas

Reputation: 359

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.

Upvotes: 3

Views: 1121

Answers (4)

FatalError
FatalError

Reputation: 54621

You can do it via indirection:

$ a10=blah
$ sala=a
$ i=10
$ ref="${sala}${i}"
$ echo $ref
a10
$ echo ${!ref}
blah

However, if you have indexes like that... an array might be more appropriate:

$ declare -a a
$ i=10
$ a[$i]="test"
$ echo ${a[$i]}
test

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 755016

The usual answer is eval:

sala=a
i=10
a10=37
eval echo "\$$sala$i"

This echoes 37. You can use "\${$sala$i}" if you prefer.

Beware of eval, especially if you need to preserve spaces in argument lists. It is vastly powerful, and vastly confusing. It will work with old shells as well as Bash, which may or may not be a merit in your eyes.

Upvotes: 1

ruakh
ruakh

Reputation: 183564

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.

Upvotes: 4

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57690

Use the eval.

eval "echo \${$sala$i}"

Put the value in another variable.

   result=$(eval "echo \${$sala$i}")

Upvotes: 1

Related Questions