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
If you want to do it in a non-destructive way, one way is to pass all the arguments to a function and return the last one:
#!/bin/bash
last() {
if [[ $# -ne 0 ]] ; then
shift $(expr $# - 1)
echo "$1"
#else
#do something when no arguments
fi
}
lastvar=$(last "$@")
echo $lastvar
echo "$@"
pax> ./qq.sh 1 2 3 a b
b
1 2 3 a b
If you don't actually care about keeping the other arguments, you don't need it in a function but I have a hard time thinking of a situation where you would never want to keep the other arguments unless they've already been processed, in which case I'd use the process/shift/process/shift/... method of sequentially processing them.
I'm assuming here that you want to keep them because you haven't followed the sequential method. This method also handles the case where there's no arguments, returning "". You could easily adjust that behavior by inserting the commented-out else clause.
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:
This works in all POSIX-compatible shells:
Source: http://www.faqs.org/faqs/unix-faq/faq/part2/section-12.html
If you want to do it in a non-destructive way, one way is to pass all the arguments to a function and return the last one:
If you don't actually care about keeping the other arguments, you don't need it in a function but I have a hard time thinking of a situation where you would never want to keep the other arguments unless they've already been processed, in which case I'd use the process/shift/process/shift/... method of sequentially processing them.
I'm assuming here that you want to keep them because you haven't followed the sequential method. This method also handles the case where there's no arguments, returning "". You could easily adjust that behavior by inserting the commented-out
else
clause.The following will set
LAST
to last argument without changing current environment:If other arguments are no longer needed and can be shifted it can be simplified to:
For portability reasons following:
can be replaced with:
Replacing also
$()
with backquotes we get:Using parameter expansion (delete matched beginning):
It's also easy to get all before last:
This is Bash-only: