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?

Jens
  • 69,818
  • 15
  • 125
  • 179
  • 1
    This is a duplicate. Same question here: http://stackoverflow.com/questions/1497811/how-to-get-the-nth-positional-argument-in-bash – Daniel Dinnyes May 25 '12 at 07:22

5 Answers5

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}
Jens
  • 69,818
  • 15
  • 125
  • 179
nosid
  • 48,932
  • 13
  • 112
  • 139
  • 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)? –  May 25 '12 at 07: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 – Andreas Wong May 25 '12 at 07:30
  • 1
    @gojira: `$@` is array-like. The expression `${!n}` in this answer is interpreted as `$2` when `n` is 2. – Dennis Williamson May 25 '12 at 11:14
15

Try this:

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

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

konqi
  • 5,137
  • 3
  • 34
  • 52
12

The following works too:

#!/bin/bash
n=2
echo ${@:$n:1}
Smi
  • 13,850
  • 9
  • 56
  • 64
5

The portable (non-bash specific) solution is

$ set a b c d
$ n=2
$ eval echo \${$n}
b
Jens
  • 69,818
  • 15
  • 125
  • 179
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

Summer_More_More_Tea
  • 12,740
  • 12
  • 51
  • 83