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

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


当前回答

$ echo "${*: -1}"

这将打印最后一个参数

其他回答

这是bash独有的:

echo "${@: -1}"

我发现@AgileZebra的答案(加上@starfry的评论)最有用,但它将头设置为一个标量。数组可能更有用:

heads=( "${@: 1: $# - 1}" )
tail=${@:${#@}}

注意,这是bash专用的。

编辑:根据@f-hauri的评论删除了不必要的$(())。

使用eval的解决方案:

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

echo $last

有一种更简洁的方法可以做到这一点。bash脚本的参数可以放入数组中,这使得元素的处理更加简单。下面的脚本将始终打印传递给脚本的最后一个参数。

  argArray=( "$@" )                        # Add all script arguments to argArray
  arrayLength=${#argArray[@]}              # Get the length of the array
  lastArg=$((arrayLength - 1))             # Arrays are zero based, so last arg is -1
  echo ${argArray[$lastArg]}

样例输出

$ ./lastarg.sh 1 2 buckle my shoe
shoe

使用结合长度的索引:

echo ${@:${#@}} 

注意,这是bash专用的。