$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

下面将在不改变当前环境的情况下将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

使用参数展开(删除匹配的开头):

args="$@"
last=${args##* }

也很容易把所有的都放在最后:

prelast=${args% *}

这是复制函数的一部分:

eval echo $(echo '$'"$#")

要在脚本中使用,请这样做:

a=$(eval echo $(echo '$'"$#"))

解释(最嵌套的先):

$(echo '$'"$#")返回$[nr],其中[nr]是参数的个数。例如字符串$123(未展开)。 Echo $123返回第123个参数的值。 Eval只是将$123扩展为参数的值,例如last_arg。它被解释为一个字符串并返回。

从2015年年中开始使用Bash。

GNU bash版本>= 3.0:

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