$1是第一个参数。 $@是全部。
如何找到传递给shell的最后一个参数 脚本?
$1是第一个参数。 $@是全部。
如何找到传递给shell的最后一个参数 脚本?
当前回答
有一种更简洁的方法可以做到这一点。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
其他回答
$ set quick brown fox jumps
$ echo ${*: -1:1} # last argument
jumps
$ echo ${*: -1} # or simply
jumps
$ echo ${*: -2:1} # next to last
fox
空格是必要的,这样它就不会被解释为默认值。
注意,这是bash专用的。
尝试下面的脚本找到最后一个参数
# 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
谢谢。
从最古老的解决方案到最新的解决方案:
最可移植的解决方案,甚至更老的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
使用结合长度的索引:
echo ${@:${#@}}
注意,这是bash专用的。
使用参数展开(删除匹配的开头):
args="$@"
last=${args##* }
也很容易把所有的都放在最后:
prelast=${args% *}