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

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


当前回答

从最古老的解决方案到最新的解决方案:

最可移植的解决方案,甚至更老的sh(适用于空格和glob字符)(没有循环,更快):

eval printf "'%s\n'" "\"\${$#}\""

从bash 2.01版开始

$ set -- The quick brown fox jumps over the lazy dog

$ printf '%s\n'     "${!#}     ${@:(-1)} ${@: -1} ${@:~0} ${!#}"
dog     dog dog dog dog

对于ksh, zsh和bash:

$ printf '%s\n' "${@: -1}    ${@:~0}"     # the space beetwen `:`
                                          # and `-1` is a must.
dog   dog

至于“倒数第二”:

$ printf '%s\n' "${@:~1:1}"
lazy

使用printf解决以破折号(如-n)开头的参数的任何问题。

对于所有shell和旧的sh(使用空格和glob字符)是:

$ set -- The quick brown fox jumps over the lazy dog "the * last argument"

$ eval printf "'%s\n'" "\"\${$#}\""
The last * argument

或者,如果你想设置最后一个变量:

$ eval last=\${$#}; printf '%s\n' "$last"
The last * argument

至于“倒数第二”:

$ eval printf "'%s\n'" "\"\${$(($#-1))}\""
dog

其他回答

#! /bin/sh

next=$1
while [ -n "${next}" ] ; do
  last=$next
  shift
  next=$1
done

echo $last

这是在将最后一个参数与所有前一个参数分开时发现的。 虽然有些答案确实得到了最后一个参数,但如果你还需要所有其他参数,它们就没有多大帮助了。这样做效果更好:

heads=${@:1:$#-1}
tail=${@:$#}

注意,这是bash专用的。

使用eval的解决方案:

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

echo $last

如果你使用的是Bash >= 3.0

echo ${BASH_ARGV[0]}
$ echo "${*: -1}"

这将打印最后一个参数