一、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'