$1是第一个参数。 $@是全部。

如何找到传递给shell的最后一个参数 脚本?


当前回答

对于bash 3.0或更高版本,最简单的答案是

_last=${!#}       # *indirect reference* to the $# variable
# or
_last=$BASH_ARGV  # official built-in (but takes more typing :)

就是这样。

$ cat lastarg
#!/bin/bash
# echo the last arg given:
_last=${!#}
echo $_last
_last=$BASH_ARGV
echo $_last
for x; do
   echo $x
done

输出是:

$ lastarg 1 2 3 4 "5 6 7"
5 6 7
5 6 7
1
2
3
4
5 6 7

其他回答

尝试下面的脚本找到最后一个参数

 # cat arguments.sh
 #!/bin/bash
 if [ $# -eq 0 ]
 then
 echo "No Arguments supplied"
 else
 echo $* > .ags
 sed -e 's/ /\n/g' .ags | tac | head -n1 > .ga
 echo "Last Argument is: `cat .ga`"
 fi

输出:

 # ./arguments.sh
 No Arguments supplied

 # ./arguments.sh testing for the last argument value
 Last Argument is: value

谢谢。

echo $argv[$#argv]

现在我只需要添加一些文字,因为我的回答太短了。我需要添加更多的文字来编辑。

这是bash独有的:

echo "${@: -1}"

GNU bash版本>= 3.0:

num=$#                 # get number of arguments
echo "${!num}"         # print last argument

对于bash,这条注释建议非常优雅:

echo "${@:$#}"

静音shellcheck,使用:

echo ${*:$#}

作为奖励,两者都可以在zsh中工作。