公告
财富商城
积分规则
提问
发文
2019-01-05 07:20发布
趁早两清
$1 is the first argument. $@ is all of them.
$1
$@
How can I find the last argument passed to a shell script?
For bash, this comment suggested the very elegant:
bash
echo "${@:$#}"
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:
-n
$ printf '%s\n' "${@:~0}" dog
And the correct way to deal with spaces and glob characters in sh is:
sh
$ 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:
last
$ eval last=\${$#}; echo "$last" The last * argument
$ eval echo "\"\${$(($#-1))}\"" dog
最多设置5个标签!
For
bash
, this comment suggested the very elegant:For ksh, zsh and bash:
And for "next to last":
To workaround any issues with arguments that start with a dash (like
-n
) use:And the correct way to deal with spaces and glob characters in
sh
is:Or, if you want to set a
last
var:And for "next to last":