22

I want to retrieve the n-th parameter of $@ (the list of command line parameters passed to the script), where n is stored in a variable.

I tried ${$n}.

For example, I want to get the 2nd command line parameter of an invocation:

./my_script.sh alpha beta gamma

And the index should not be explicit but stored in a variable n.

Sourcecode:

n=2
echo ${$n}

I would expect the output to be "beta", but I get the error:

./my_script.sh: line 2: ${$n}: bad substitution

What am I doing wrong?

1

5 Answers 5

40

You can use variable indirection. It is independent of arrays, and works fine in your example:

n=2
echo "${!n}"

Edit: Variable Indirection can be used in a lot of situations. If there is a variable foobar, then the following two variable expansions produce the same result:

$foobar

name=foobar
${!name}
3
  • Thanks. I'm sure this works too but I do not understand why. Why "nothing to do with arrays"?! Isn't $@ a list (not an array)?
    – user438602
    Commented May 25, 2012 at 7:27
  • @gojira I think the point nosid is making is that you don't even need to copy the list of arguments separately, and could just reference it by using variable indirection Commented May 25, 2012 at 7:30
  • 1
    @gojira: $@ is array-like. The expression ${!n} in this answer is interpreted as $2 when n is 2. Commented May 25, 2012 at 11:14
15

Try this:

#!/bin/bash
args=("$@")
echo ${args[1]}

okay replace the "1" with some $n or something...

0
12

The following works too:

#!/bin/bash
n=2
echo ${@:$n:1}
1
  • The dollar sign before the n can be omitted. Commented May 25, 2012 at 11:16
5

The portable (non-bash specific) solution is

$ set a b c d
$ n=2
$ eval echo \${$n}
b
1
2

eval can help you access the variable indirectly, which means evaluate the expression twice.

You can do like this eval alph=\$$n; echo $alph

Your Answer

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