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条回答
太酷不给撩
2楼-- · 2019-01-05 08:02

For bash, this comment suggested the very elegant:

echo "${@:$#}"
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-05 08:03

For ksh, zsh and bash:

$ set -- The quick brown fox jumps over the lazy dog

$ echo "${@:~0}"
dog

And for "next to last":

$ echo "${@:~1:1}"
lazy

To workaround any issues with arguments that start with a dash (like -n) use:

$ printf '%s\n' "${@:~0}"
dog

And the correct way to deal with spaces and glob characters in sh is:

$ set -- The quick brown fox jumps over the lazy dog "the * last argument"

$ eval echo "\"\${$#}\""
The last * argument

Or, if you want to set a last var:

$ eval last=\${$#}; echo "$last"
The last * argument

And for "next to last":

$ eval echo "\"\${$(($#-1))}\""
dog
查看更多
登录 后发表回答