$1是第一个参数。 $@是全部。
如何找到传递给shell的最后一个参数 脚本?
$1是第一个参数。 $@是全部。
如何找到传递给shell的最后一个参数 脚本?
当前回答
这是bash独有的:
echo "${@: -1}"
其他回答
GNU bash版本>= 3.0:
num=$# # get number of arguments
echo "${!num}" # print last argument
只需使用!$。
$ mkdir folder
$ cd !$ # will run: cd folder
以下是我的解决方案:
相当可移植(所有POSIX sh, bash, ksh, zsh)应该工作 不移位原始参数(移位副本)。 不使用恶eval 不是遍历整个列表 不使用外部工具
代码:
ntharg() {
shift $1
printf '%s\n' "$1"
}
LAST_ARG=`ntharg $# "$@"`
$ set quick brown fox jumps
$ echo ${*: -1:1} # last argument
jumps
$ echo ${*: -1} # or simply
jumps
$ echo ${*: -2:1} # next to last
fox
空格是必要的,这样它就不会被解释为默认值。
注意,这是bash专用的。
在阅读了上面的答案后,我写了一个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