$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

其他回答

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

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

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

如果你使用的是Bash >= 3.0

echo ${BASH_ARGV[0]}
$ set quick brown fox jumps

$ echo ${*: -1:1} # last argument
jumps

$ echo ${*: -1} # or simply
jumps

$ echo ${*: -2:1} # next to last
fox

空格是必要的,这样它就不会被解释为默认值。

注意,这是bash专用的。

有一种更简洁的方法可以做到这一点。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

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

 # 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

谢谢。