Getting the last argument passed to a shell script

ID : 10317

viewed : 17

Tags : shellargumentsshell

Top 5 Answer for Getting the last argument passed to a shell script

vote vote

94

This is Bash-only:

echo "${@: -1}" 
vote vote

86

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.

vote vote

78

$ set quick brown fox jumps  $ echo ${*: -1:1} # last argument jumps  $ echo ${*: -1} # or simply jumps  $ echo ${*: -2:1} # next to last fox 

The space is necessary so that it doesn't get interpreted as a default value.

Note that this is bash-only.

vote vote

61

The simplest answer for bash 3.0 or greater is

_last=${!#}       # *indirect reference* to the $# variable # or _last=$BASH_ARGV  # official built-in (but takes more typing :) 

That's it.

$ cat lastarg #!/bin/bash # echo the last arg given: _last=${!#} echo $_last _last=$BASH_ARGV echo $_last for x; do    echo $x done 

Output is:

$ lastarg 1 2 3 4 "5 6 7" 5 6 7 5 6 7 1 2 3 4 5 6 7 
vote vote

50

The following will work for you. The @ is for array of arguments. : means at. $# is the length of the array of arguments. So the result is the last element:

${@:$#}  

Example:

function afunction{     echo ${@:$#}  } afunction -d -o local 50 #Outputs 50 

Note that this is bash-only.

Top 3 video Explaining Getting the last argument passed to a shell script

Related QUESTION?