Getting the last argument passed to a shell script Getting the last argument passed to a shell script shell shell

Getting the last argument passed to a shell script


This is Bash-only:

echo "${@: -1}"


This is a bit of a hack:

for last; do true; doneecho $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.


$ set quick brown fox jumps$ echo ${*: -1:1} # last argumentjumps$ echo ${*: -1} # or simplyjumps$ echo ${*: -2:1} # next to lastfox

The space is necessary so that it doesnt get interpreted as a default value.

Note that this is bash-only.