Thomas Thomas - 6 months ago 16
Bash Question

Getting the last argument passed to a shell script

$1
is the first argument.

$@
is all of them.

How can I find the last argument passed to a shell
script?

Answer

This is a bit of a hack:

for last; do true; done
echo $last

This one is also pretty portable (again, should work with bash, ksh and sh) and it doesn't shift the arguments, which could be nice.

It uses the fact that for implicitly loops over the arguments if you don't tell it what to loop over, and the fact that for loop variables aren't scoped: they keep the last value they were set to.