3

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.

1
  • What are you doing? Sounds like you need an array. Commented Feb 27, 2012 at 21:48

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@user1236560: You're welcome! But I see now that a few people have suggested that you use an array, which I think is a good idea: instead of having variables named $a10, $b7, and so on -- if that's what you have -- you can have an array named arr with indices like 'a10' and 'b7' and so on. That would let you write simply "${arr[$sala$i]}".
this wont work because I cannot put something different than numbers in the index of the array
@user1236560: Yeah, I'm not surprised. Bash only added support for e.g. ${arr[a10]} in version 4.0, and a lot of machines are still running 3.x versions.
1

Use the eval.

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

Put the value in another variable.

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

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.