I need to indirectly reference a variable in the bash shell.

I basically want to what you can do in make by writing $($(var)).

I have tried using ${$var} which would be the most straight forward solution in bash but then I get this error:

bash: ${$var}: bad substitution

Is there a way to do this?

What I am trying to do is to iterate over all the arguments ($1, $2, $3, ...) to a program using an iteration variable and I cannot do this without indirection.


If you have var1=foo and foo=bar, you can get bar by saying ${!var1}. However, if you want to iterate over the positional parameters, it's almost certainly better to do

for i in "$@"; do
    # something
  • Is there a way to add multiple levels of indirection?
    – wefwefa3
    Sep 17 '15 at 12:44
  • 1
    Not that I can quickly find. The obvious guess of ${!!var1} doesn't work. However, you can always do it manually, e.g. tmp=${!var1}; echo ${!tmp}.
    – Tom Hunt
    Sep 17 '15 at 15:05

Using /bin/bash:

echo ${!test}

# prints -> bar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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