$1是第一个参数。 $@是全部。
如何找到传递给shell的最后一个参数 脚本?
$1是第一个参数。 $@是全部。
如何找到传递给shell的最后一个参数 脚本?
当前回答
#! /bin/sh
next=$1
while [ -n "${next}" ] ; do
last=$next
shift
next=$1
done
echo $last
其他回答
#! /bin/sh
next=$1
while [ -n "${next}" ] ; do
last=$next
shift
next=$1
done
echo $last
这是bash独有的:
echo "${@: -1}"
在阅读了上面的答案后,我写了一个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
这是复制函数的一部分:
eval echo $(echo '$'"$#")
要在脚本中使用,请这样做:
a=$(eval echo $(echo '$'"$#"))
解释(最嵌套的先):
$(echo '$'"$#")返回$[nr],其中[nr]是参数的个数。例如字符串$123(未展开)。 Echo $123返回第123个参数的值。 Eval只是将$123扩展为参数的值,例如last_arg。它被解释为一个字符串并返回。
从2015年年中开始使用Bash。
shift `expr $# - 1`
echo "$1"
这将参数移位为参数的数量减1,并返回第一个(也是唯一一个)剩余的参数,这将是最后一个参数。
我只在bash中测试,但它应该也能在sh和ksh中工作。