Getting the last argument passed to a shell script

2019-01-05 07:20发布

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

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

26条回答
Animai°情兽
2楼-- · 2019-01-05 07:36

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
查看更多
唯我独甜
3楼-- · 2019-01-05 07:37

This works in all POSIX-compatible shells:

eval last=\${$#}

Source: http://www.faqs.org/faqs/unix-faq/faq/part2/section-12.html

查看更多
萌系小妹纸
4楼-- · 2019-01-05 07:38

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.

查看更多
我命由我不由天
5楼-- · 2019-01-05 07:39

The following will set LAST to last argument without changing current environment:

LAST=$({
   shift $(($#-1))
   echo $1
})
echo $LAST

If other arguments are no longer needed and can be shifted it can be simplified to:

shift $(($#-1))
echo $1

For portability reasons following:

shift $(($#-1));

can be replaced with:

shift `expr $# - 1`

Replacing also $() with backquotes we get:

LAST=`{
   shift \`expr $# - 1\`
   echo $1
}`
echo $LAST
查看更多
Bombasti
6楼-- · 2019-01-05 07:41

Using parameter expansion (delete matched beginning):

args="$@"
last=${args##* }

It's also easy to get all before last:

prelast=${args% *}
查看更多
Explosion°爆炸
7楼-- · 2019-01-05 07:42

This is Bash-only:

echo "${@: -1}"
查看更多
登录 后发表回答