UNIX系统变量
$? 前一个命令或函数的返回码
$# 参数数目
$0,1,2,3
$0是程序本体,从$1,$2,$3是参数
$*
字符串:以"参数1 参数2 ... " 形式保存所有参数
$@
字符串数组:以"参数1" "参数2" ... 的字符串数组形式保存所有参数
$$ 本程序的(进程ID号)PID
$? 最后一条命令的返回码 (成功0,失败1)
常用返回码$?判断程序是否异常退出,是否执行失败
标准的命令行参数处理机制----用shelf依次处理命令行参数――只处理$1(第一个参数),shift,直到$1为空
最典型的单参数命令行,用于sys v启动脚本的start|stop|restart|status处理
shell程序的传参的几种方法
1.命令行参数
2.read 参数
3.读配置文件
检验命令行参数数目
用简化 if 和$1,$2,$3来检测参数,不合理就调用help
[ -z "$1" ] && help
如果第一个参数不存在(-z
字符串长度为0 )
[ "$1" = "-h" ] && help
如果第一个参数是-h,就显示help
$?
$#
$0,1,2,3
$*
$@
$$
$ ls 111.txt 111.txt $ echo $? 0 前一条命令成功,返回0 |
[macg@machome ~]$ ls sdsdf ls: sdsdf: No such file or directory [macg@machome ~]$ echo $? 1 前一条命令失败(出错),返回1 |
[mac@machome ~]$ vi test.sh ls -l $1 if [ $? != 0 ] ;then echo command fail else echo command success fi |
[mac@machome ~]$ sh test.sh 111.txt -rw-rw-r-- command success [mac@machome ~]$ sh test.sh 222.txt ls: 222.txt: No such file or directory command fail |
while [ -n "$1" ]; do 为什么循环总是$1(第一个参数)? case $1 in -h) h=$1 echo "your choice is $h" -f) f=$1 echo "your choice is $f" -c) c=$1 echo "your choice is $c" -z) z=$1 echo "your choice is $z" *) echo " $1 is wrong paratism" 不符合条件的参数,不再循环(break)(等于以后的参数不再检查) esac done |
[macg@machome ~]$ sh test.sh -h -z -c -f your choice is -h your choice is -z your choice is -c your choice is -f [macg@machome ~]$ sh test.sh -6 -h -6 is wrong paratism [macg@machome ~]$ sh test.sh -h -z -6 your choice is -h your choice is -z |
case start) stop) restart) status) |
1.命令行参数
$0 $1 $2 |
echo –n “ …:” read … |
aa=`cat param.txt | gawk '/input:/{print $1}'` echo "aa is $aa" $ sh tb.sh aa is echo |
如果参数没输全时([ $# -lt 3 ]),显示这个help if [ $# lt 3 ] ;then fi |
[macg @machome ~]$ sh test.sh 23 23 test.sh: line 18: [: lt: binary operator expected |
错在哪里? 改成if [ $# -lt 3 ] ;then |
[ -z "$1" ] && help
[ "$1" = "-h" ] && help