$1是第一个参数。 $@是全部。
如何找到传递给shell的最后一个参数 脚本?
$1是第一个参数。 $@是全部。
如何找到传递给shell的最后一个参数 脚本?
当前回答
下面的方法对你有用。
@是参数数组。 :表示at $#是参数数组的长度。
所以结果是最后一个元素:
${@:$#}
例子:
function afunction{
echo ${@:$#}
}
afunction -d -o local 50
#Outputs 50
注意,这是bash专用的。
其他回答
shift `expr $# - 1`
echo "$1"
这将参数移位为参数的数量减1,并返回第一个(也是唯一一个)剩余的参数,这将是最后一个参数。
我只在bash中测试,但它应该也能在sh和ksh中工作。
尝试下面的脚本找到最后一个参数
# 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
谢谢。
对于bash,这条注释建议非常优雅:
echo "${@:$#}"
静音shellcheck,使用:
echo ${*:$#}
作为奖励,两者都可以在zsh中工作。
要返回最近使用的命令的最后一个参数,请使用特殊形参:
$_
在这个实例中,如果在调用另一个命令之前在脚本中使用它,那么它将工作。
在阅读了上面的答案后,我写了一个Q&D shell脚本(应该在sh和bash上工作)在PGM.cpp上运行g++以生成可执行的图像PGM。它假设命令行上的最后一个参数是文件名(.cpp是可选的),所有其他参数都是选项。
#!/bin/sh
if [ $# -lt 1 ]
then
echo "Usage: `basename $0` [opt] pgm runs g++ to compile pgm[.cpp] into pgm"
exit 2
fi
OPT=
PGM=
# PGM is the last argument, all others are considered options
for F; do OPT="$OPT $PGM"; PGM=$F; done
DIR=`dirname $PGM`
PGM=`basename $PGM .cpp`
# put -o first so it can be overridden by -o specified in OPT
set -x
g++ -o $DIR/$PGM $OPT $DIR/$PGM.cpp