$1是第一个参数。 $@是全部。
如何找到传递给shell的最后一个参数 脚本?
$1是第一个参数。 $@是全部。
如何找到传递给shell的最后一个参数 脚本?
当前回答
我发现@AgileZebra的答案(加上@starfry的评论)最有用,但它将头设置为一个标量。数组可能更有用:
heads=( "${@: 1: $# - 1}" )
tail=${@:${#@}}
注意,这是bash专用的。
编辑:根据@f-hauri的评论删除了不必要的$(())。
其他回答
对于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
#! /bin/sh
next=$1
while [ -n "${next}" ] ; do
last=$next
shift
next=$1
done
echo $last
如果你使用的是Bash >= 3.0
echo ${BASH_ARGV[0]}
在阅读了上面的答案后,我写了一个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
这是在将最后一个参数与所有前一个参数分开时发现的。 虽然有些答案确实得到了最后一个参数,但如果你还需要所有其他参数,它们就没有多大帮助了。这样做效果更好:
heads=${@:1:$#-1}
tail=${@:$#}
注意,这是bash专用的。