获取命令行中最后一个参数(${!#})

获取命令行中最后一个参数(${!#})

Content #

特殊变量$#含有脚本运行时携带的命令行参数的个数。

这个变量还提供了一种简便方法来获取命令行中最后一个参数,完全不需要知道实际上到底用了多少个参数。

如果仔细考虑过,你可能会觉得既然$#变量含有命令行参数的总数,那么变量 \({\)#}应该就代表了最后一个位置变量。试试看会发生什么:

$ cat badlastparamtest.sh
#!/bin/bash
# Testing grabbing the last parameter
#
echo The number of parameters is $#
echo The last parameter is ${$#}
exit
$
$ ./badlastparamtest.sh one two three four
The number of parameters is 4
The last parameter is 2648
$

显然,这种方法不管用。这说明不能在花括号内使用$,必须将$换成!。很奇怪,但的确有效:

$ cat goodlastparamtest.sh
#!/bin/bash
# Testing grabbing the last parameter
#
echo The number of parameters is $#
echo The last parameter is ${!#}
exit
$
$ ./goodlastparamtest.sh one two three four
The number of parameters is 4
The last parameter is four
$
$ ./goodlastparamtest.sh
The number of parameters is 0
The last parameter is ./goodlastparamtest.sh
$

当命令行中没有任何参数时,\(#的值即为0,但\){!#}会返回命令行中的脚本名。

From #

Linux命令行与shell脚本编程大全