$1是第一个参数。 $@是全部。
如何找到传递给shell的最后一个参数 脚本?
$1是第一个参数。 $@是全部。
如何找到传递给shell的最后一个参数 脚本?
当前回答
只需使用!$。
$ mkdir folder
$ cd !$ # will run: cd folder
其他回答
如果你使用的是Bash >= 3.0
echo ${BASH_ARGV[0]}
对于bash,这条注释建议非常优雅:
echo "${@:$#}"
静音shellcheck,使用:
echo ${*:$#}
作为奖励,两者都可以在zsh中工作。
从最古老的解决方案到最新的解决方案:
最可移植的解决方案,甚至更老的sh(适用于空格和glob字符)(没有循环,更快):
eval printf "'%s\n'" "\"\${$#}\""
从bash 2.01版开始
$ set -- The quick brown fox jumps over the lazy dog
$ printf '%s\n' "${!#} ${@:(-1)} ${@: -1} ${@:~0} ${!#}"
dog dog dog dog dog
对于ksh, zsh和bash:
$ printf '%s\n' "${@: -1} ${@:~0}" # the space beetwen `:`
# and `-1` is a must.
dog dog
至于“倒数第二”:
$ printf '%s\n' "${@:~1:1}"
lazy
使用printf解决以破折号(如-n)开头的参数的任何问题。
对于所有shell和旧的sh(使用空格和glob字符)是:
$ set -- The quick brown fox jumps over the lazy dog "the * last argument"
$ eval printf "'%s\n'" "\"\${$#}\""
The last * argument
或者,如果你想设置最后一个变量:
$ eval last=\${$#}; printf '%s\n' "$last"
The last * argument
至于“倒数第二”:
$ eval printf "'%s\n'" "\"\${$(($#-1))}\""
dog
尝试下面的脚本找到最后一个参数
# 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
谢谢。
下面将在不改变当前环境的情况下将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