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

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


当前回答

$ echo "${*: -1}"

这将打印最后一个参数

其他回答

使用eval的解决方案:

last=$(eval "echo \$$#")

echo $last

GNU bash版本>= 3.0:

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

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

 # 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 ${@:${#@}} 

注意,这是bash专用的。

shift `expr $# - 1`
echo "$1"

这将参数移位为参数的数量减1,并返回第一个(也是唯一一个)剩余的参数,这将是最后一个参数。

我只在bash中测试,但它应该也能在sh和ksh中工作。