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

5

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?

Weathering answered 25/5, 2012 at 7:5 Comment(1)
This is a duplicate. Same question here: #1498311Terrorist
K
15

Try this:

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

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

Kortneykoruna answered 25/5, 2012 at 7:14 Comment(0)
H
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}
Hent answered 25/5, 2012 at 7:12 Comment(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)?Weathering
@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 indirectionElwandaelwee
@gojira: $@ is array-like. The expression ${!n} in this answer is interpreted as $2 when n is 2.Newness
K
15

Try this:

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

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

Kortneykoruna answered 25/5, 2012 at 7:14 Comment(0)
L
12

The following works too:

#!/bin/bash
n=2
echo ${@:$n:1}
Leatherwood answered 25/5, 2012 at 7:19 Comment(1)
The dollar sign before the n can be omitted.Newness
I
5

The portable (non-bash specific) solution is

$ set a b c d
$ n=2
$ eval echo \${$n}
b
Iritis answered 25/5, 2012 at 7:16 Comment(1)
@gojira: You should be aware of the security implications.Newness
P
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

Pero answered 25/5, 2012 at 7:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.