1、参数计数
特殊变量$#中存储执行脚本时包含的命令行参数的个数,在脚本的任意位置都可以使用这个特殊变量,就像使用普通变量一样。
[root@ASM ~]# cat t11.sh
#!/bin/bash
echo there were $# parameters supplied.
[root@ASM ~]# ./t11.sh 7 8 9
there were 3 parameters supplied.
[root@ASM ~]# ./t11.sh 7 8 9 78
there were 4 parameters supplied.
使用参数前测试参数的个数
[root@ASM ~]# cat t12.sh
#!/bin/bash
if [ $# -ne 2 ]
then
echo usage: a b
else
total=$[ $1 * $2 ]
echo the total is $total
fi
[root@ASM ~]# ./t12.sh
usage: a b
[root@ASM ~]# ./t12.sh 2
usage: a b
[root@ASM ~]# ./t12.sh 2 4
the total is 8
既然$#代表命令行参数的个数,那么$[$#]能代表最后一个参数的值么?
[root@ASM ~]# cat t13.sh
#!/bin/bash
echo the last parameter is ${$#}
[root@ASM ~]# ./t13.sh 34
the last parameter is 7515 ---这个结果表明在大括号中不能使用美元符号,必须将美元符号换为感叹号
[root@ASM ~]# cat t13.sh
#!/bin/bash
echo the last parameter is ${!#} ---这里必须使用大括号
[root@ASM ~]# ./t13.sh 4
the last parameter is 4
[root@ASM ~]# ./t13.sh 4 6 8
the last parameter is 8
**当没有输入命令行参数时${!#}返回命令行中使用的脚本的名称
2、获取所有数据
$*和$@用于获取命令行中所有的参数,不同之处是:$*将所有参数视为一个字符串;$@将各个参数分别对待。
[root@ASM ~]# cat t14.sh
#!/bin/bash
#testing $* and $@
count=1
for para in "$*"
do
echo "\$* parameter $count=$para"
count=$[ $count + 1 ]
done
count=1
for para in "$@"
do
echo "\$@ parameter $count=$para"
count=$[ $count + 1 ]
done
[root@ASM ~]# ./t14.sh welcome to china
$* parameter 1=welcome to china
$@ parameter 1=welcome
$@ parameter 2=to
$@ parameter 3=china
3、移位操作
shift用于向左移位命令行参数
[root@ASM ~]# cat t17.sh
#!/bin/bash
while [ -n "$1" ] ---本例中$1一直存在的原因就是循环中使用了shift向左移动了移位
do
echo parameter $1
shift 1
done
[root@ASM ~]# ./t17.sh 3 5 7
parameter 3
parameter 5
parameter 7
[root@ASM ~]# cat t18.sh
#!/bin/bash
echo the original parameters: $*
shift 2 -----左移两位之后$*的值变了
echo the new original parameters: $@
[root@ASM ~]# ./t18.sh 1 2 3 4 5
the original parameters: 1 2 3 4 5
the new original parameters: 3 4 5
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/23655288/viewspace-734915/
,如需转载,请注明出处,否则将追究法律责任。