$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

在阅读了上面的答案后,我写了一个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

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

最可移植的解决方案,甚至更老的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

下面的方法对你有用。

@是参数数组。 :表示at $#是参数数组的长度。

所以结果是最后一个元素:

${@:$#} 

例子:

function afunction{
    echo ${@:$#} 
}
afunction -d -o local 50
#Outputs 50

注意,这是bash专用的。

以下是我的解决方案:

相当可移植(所有POSIX sh, bash, ksh, zsh)应该工作 不移位原始参数(移位副本)。 不使用恶eval 不是遍历整个列表 不使用外部工具

代码:

ntharg() {
    shift $1
    printf '%s\n' "$1"
}
LAST_ARG=`ntharg $# "$@"`