$1是第一个参数。 $@是全部。
如何找到传递给shell的最后一个参数 脚本?
$1是第一个参数。 $@是全部。
如何找到传递给shell的最后一个参数 脚本?
当前回答
shift `expr $# - 1`
echo "$1"
这将参数移位为参数的数量减1,并返回第一个(也是唯一一个)剩余的参数,这将是最后一个参数。
我只在bash中测试,但它应该也能在sh和ksh中工作。
其他回答
尝试下面的脚本找到最后一个参数
# cat arguments.sh
#!/bin/bash
if [ $# -eq 0 ]
then
echo "No Arguments supplied"
else
echo $* > .ags
sed -e 's/ /\n/g' .ags | tac | head -n1 > .ga
echo "Last Argument is: `cat .ga`"
fi
输出:
# ./arguments.sh
No Arguments supplied
# ./arguments.sh testing for the last argument value
Last Argument is: value
谢谢。
GNU bash版本>= 3.0:
num=$# # get number of arguments
echo "${!num}" # print last argument
#! /bin/sh
next=$1
while [ -n "${next}" ] ; do
last=$next
shift
next=$1
done
echo $last
使用参数展开(删除匹配的开头):
args="$@"
last=${args##* }
也很容易把所有的都放在最后:
prelast=${args% *}
对于bash,这条注释建议非常优雅:
echo "${@:$#}"
静音shellcheck,使用:
echo ${*:$#}
作为奖励,两者都可以在zsh中工作。