$1是第一个参数。 $@是全部。

如何找到传递给shell的最后一个参数 脚本?


当前回答

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

其他回答

这是bash独有的:

echo "${@: -1}"

GNU bash版本>= 3.0:

num=$#                 # get number of arguments
echo "${!num}"         # print last argument

这是一个小hack:

for last; do true; done
echo $last

这也是非常可移植的(同样,应该与bash、ksh和sh一起工作),并且它不改变参数,这可能很好。

它利用了这样一个事实:如果你不告诉它循环什么,for会隐式地遍历参数,而且for循环变量没有作用域:它们保持它们设置的最后一个值。

下面将在不改变当前环境的情况下将LAST设置为最后一个参数:

LAST=$({
   shift $(($#-1))
   echo $1
})
echo $LAST

如果其他参数不再需要并且可以被转移,则可以简化为:

shift $(($#-1))
echo $1

出于便携性的考虑:

shift $(($#-1));

可替换为:

shift `expr $# - 1`

同样用反引号替换$(),我们得到:

LAST=`{
   shift \`expr $# - 1\`
   echo $1
}`
echo $LAST
#! /bin/sh

next=$1
while [ -n "${next}" ] ; do
  last=$next
  shift
  next=$1
done

echo $last