BASH scripting: n-th parameter of $@ when the index is a variable?

user438602 picture user438602 · May 25, 2012 · Viewed 14.2k times · Source

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?

Answer

nosid picture nosid · May 25, 2012

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}