Shell script的语法三:设置参数

一、script中命令的变量名

该变量名已系统预定义,如下:

/path/to/scriptname  opt1  opt2  opt3  opt4 
          ${0}                    ${1}    ${2}  ${3}   ${4}

执行的脚本名称为${0}这个变量名,接的第一个参数的变量名是${1},第二个参数的变量名是${2}……

除了这些数字的变量名,还有一些比较特殊的变量名可以在script中引用:

1)$#   :代表执行脚本后接参数的 个数,实例中这里显示  4 ;

2)$@ :代表  ${1} ${2} ${3} ${4} 的值,每个参数是独立的;

3)$*   :代表  "${1}c${2}c${3}c${4}" ,其中 c 为分隔字符,初始值为空白健, 所以本例中代表${1} ${2} ${3} ${4} 的值

$@ 与 $* 基本上是有区别的,不过,一般使用情況下可以直接使用$@ 即可! 

二、在script使用变量名的示例

例如执行一个可带参数的script:

#!/bin/bash
#Program
#  Program shows the script name,parameters...
#History:
#2017/01/10 shu First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

echo "The script name is ==>${0}"
echo "Total parameter number is ==>$#"
[ "$#" -lt 2 ] && echo "The number of parameter is less than 2. Stop here." && exit 0
echo "Your whole parameter is ==>'$@'"
echo "The first parameter ==>${1}"
echo "The second parameter ==>${2}"
echo "The third parameter ==>${3}"
执行结果如下:

root@Test:~/bin$ sh how_paras.sh theone two quot
The script name is ==>how_paras.sh
Total parameter number is ==>3
Your whole parameter is ==>'theone two quot'
The first parameter ==>theone
The second parameter ==>two
The third parameter ==>quot
三、使用shift 移动命令参数的变量名号码

shift 可以移动参数的变量名数字,而且 shift 后可以接数字,代表拿掉最前面的几个参数的意思,例如:

#!/bin/bash
#Program:
#  program shows the effect of shift function.
#History:
#2017/01/10 shu First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

echo "The script name is ==>${0}"
echo "Total parameter number is ==>$#"
echo "Your whole parameter is ==>'$@'"
shift #进行第一次“移动一个变量名”
echo "Total parameter number is ==>$#"
echo "Your whole parameter is ==>'$@'"
shift 3 #进行第二次“移动3个变量名”
echo "Total parameter number is ==>$#"
echo "Your whole parameter is ==>'$@'"

执行结果:

root@Test:~/program/bin$ sh shift_paras.sh one two three four five six
The script name is ==>shift_paras.sh
Total parameter number is ==>6
Your whole parameter is ==>'one two three four five six'
Total parameter number is ==>5
Your whole parameter is ==>'two three four five six'
Total parameter number is ==>2
Your whole parameter is ==>'five six'



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值