linuxSHELL学习之特殊参数

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博客 ” ,链接:http://blog.itpub.net/23655288/viewspace-734915/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/23655288/viewspace-734915/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值