Monday, April 11, 2022

[SOLVED] Getting the last argument passed to a shell script

Issue

$1 is the first argument.
$@ is all of them.

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


Solution

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.



Answered By - Laurence Gonsalves
Answer Checked By - Mary Flores (WPSolving Volunteer)