nullByteMe
nullByteMe

Reputation: 6391

Unable to set second to last command line argument to variable

Regardless of the number of arguments passed to my script, I would like for the second to the last argument to always represent a specific variable in my code.

Executing the program I'd type something like this:

sh myprogram.sh -a arg_a -b arg_b special specific

test=("${3}")
echo $test

The results will show 'special'. So using that same idea if I try this (since I won't know that number of arguments):

secondToLastArg=$(($#-1))
echo $secondToLastArg

The results will show '3'. How do I dynamically assign the second to last argument?

Upvotes: 2

Views: 120

Answers (2)

anishsane
anishsane

Reputation: 20980

You can use $@ as array & array chopping methods:

echo ${@:$(($#-1)):1}

It means, use 1 element starting from $(($#-1))...

If some old versions of shells do not support ${array:start:length} syntax but support only ${array:start} syntax, use below hack:

echo ${@:$(($#-1))} | { read x y ; echo $x; } # OR
read x unused <<< `echo ${@:$(($#-1))}`

Upvotes: 2

Kevin
Kevin

Reputation: 56059

You need a bit of math to get the number you want ($(($#-1))), then use indirection (${!n}) to get the actual argument.

$ set -- a b c 
$ echo $@
a b c
$ n=$(($#-1))
$ echo $n
2
$ echo ${!n}
b
$ 

Indirection (${!n}) tells bash to use the value of n as the name of the variable to use ($2, in this case).

Upvotes: 3

Related Questions