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 07:43
echo $argv[$#argv]

Now I just need to add some text because my answer was too short to post. I need to add more text to edit.

查看更多
乱世女痞
3楼-- · 2019-01-05 07:46
$ 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 doesnt get interpreted as a default value.

查看更多
爷的心禁止访问
4楼-- · 2019-01-05 07:46

For tcsh:

set X = `echo $* | awk -F " " '{print $NF}'`
somecommand "$X"

I'm quite sure this would be a portable solution, except for the assignment.

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-05 07:46

I found @AgileZebra's answer (plus @starfry's comment) the most useful, but it sets heads to a scalar. An array is probably more useful:

heads=( "${@:1:$(($# - 1))}" )
tail=${@:${#@}}
查看更多
甜甜的少女心
6楼-- · 2019-01-05 07:47

If you are using Bash >= 3.0

echo ${BASH_ARGV[0]}
查看更多
该账号已被封号
7楼-- · 2019-01-05 07:47

This is part of my copy function:

eval echo $(echo '$'"$#")

To use in scripts, do this:

a=$(eval echo $(echo '$'"$#"))

Explanation (most nested first):

  1. $(echo '$'"$#") returns $[nr] where [nr] is the number of parameters. E.g. the string $123 (unexpanded).
  2. echo $123 returns the value of 123rd parameter, when evaluated.
  3. eval just expands $123 to the value of the parameter, e.g. last_arg. This is interpreted as a string and returned.

Works with Bash as of mid 2015.

查看更多
登录 后发表回答