Bash:获取传递给Shell脚本的最后一个参数

时间:2020-01-09 10:42:06  来源:igfitidea点击:

我正在编写一个bash包装器脚本,该脚本会将参数传递给命令。
如果我按如下方式调用包装器,则需要找出最后一个参数:

./wrapper -a -b longarg=foo thisfilename.txt ./wrapper -a -b thisfilename.txt ./wrapper -a next=true thisfilename.txt

其中,

  • $@整个命令行。

  • $0是脚本名称。

  • $1是第一个参数。

我希望将此文件名.txt存储在名为$last的shell变量中。
我如何找到传递给Unix之类的以bash或者ksh编写的shell脚本的最后一个参数?

您可以使用以下任何一种语法找到传递给shell脚本的最后一个参数:

## only works with bash / ksh ##
echo "${@: -1}"

以下内容仅适用于bash v3.x +:

echo "${BASH_ARGV[0]}"

一个示例shell脚本:

#!/bin/bash
echo "Last argument only (works with bash/ksh only): ${@: -1}"
echo "Last argument only (works with bash 3.x+ only): ${!#}"
echo "Last argument only (works with bash 3.x+ only): $BASH_ARGV"
echo "Last argument only (works with bash 3.x+ / ksh only): ${@:$#}"
echo "Last argument only (works with bash 3.x+ only): ${BASH_ARGV[0]}"
echo -n "Last argument only (portable version): "
for i in $@; do :; done
echo "$i"

如下运行:

$ ./script -a -b --foo thisfilename.txt

输出示例:

Last argument only (works with bash/ksh only): thisfilename.txt
Last argument only (works with bash 3.x+ only): thisfilename.txt
Last argument only (works with bash 3.x+ only): thisfilename.txt
Last argument only (works with bash 3.x+ / ksh only): thisfilename.txt
Last argument only (works with bash 3.x+ only): thisfilename.txt
Last argument only (portable version): thisfilename.txt

另一个测试:

$ ./script -a -b --foo --next=true thisfilename.txt

输出示例:

Last argument only (works with bash/ksh only): thisfilename.txt
Last argument only (works with bash 3.x+ only): thisfilename.txt
Last argument only (works with bash 3.x+ only): thisfilename.txt
Last argument only (works with bash 3.x+ / ksh only): thisfilename.txt
Last argument only (works with bash 3.x+ only): thisfilename.txt
Last argument only (portable version): thisfilename.txt

关于便携式版本的注意事项

如下代码:

for i in $@; do :; done
echo "Last arg : $i"

可以写成如下:

#-----------------------------------------------------------------------------------------#
# How does it works? 
# If you do not tell what to loop over shell will loop over the arguments i.e. $@ .  
# This is a default. 
#-----------------------------------------------------------------------------------------#
for i; do :; done
echo "Last arg : $i"

它应该可以与sh,ksh和bash一起使用,而不会出现任何问题。