UNIX系统变量
$? 前一个命令或函数的返回码
$# 参数数目
$0,1,2,3 $0是程序本体,从$1,$2,$3是参数
$* 字符串:以"参数1 参数2 ... " 形式保存所有参数
$@ 字符串数组:以"参数1" "参数2" ... 的字符串数组形式保存所有参数
$$ 本程序的(进程ID号)PID
$? 最后一条命令的返回码 (成功0,失败1)
$ 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-- 1 mac mac 0 Jun 7 19:35 111.txt command success [mac@machome ~]$ sh test.sh 222.txt ls: 222.txt: No such file or directory command fail |
标准的命令行参数处理机制----用shelf依次处理命令行参数――只处理$1(第一个参数),shift,直到$1为空
while [ -n "$1" ]; do 为什么循环总是$1(第一个参数)? case $1 in -h) h=$1 echo "your choice is $h" shift使参数依次前移 shift;; -f) f=$1 echo "your choice is $f" shift;; -c) c=$1 echo "your choice is $c" shift;; -z) z=$1 echo "your choice is $z" shift;; *) echo " $1 is wrong paratism" break;; 不符合条件的参数,不再循环(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 -6 is wrong paratism |
最典型的单参数命令行,用于sys v启动脚本的start|stop|restart|status处理
case "$@" in start) echo -n "Starting firewall..." 。。。 echo "OK!" exit 0 ;; stop) echo -n "Stopping firewall..." 。。。 exit 0 ;; restart) $0 stop $0 start ;; status) clear echo ">------------------------------------------" iptables -L echo ">------------------------------------------" iptables -t nat -L POSTROUTING exit 0 *) echo "Usage: $0 {start|stop|restart|status}" $0即执行原始程序 exit 1 esac |
shell程序的传参的几种方法
1.命令行参数
$0 $1 $2 $n |
2.read 参数
echo –n “ …:” read … |
3.读配置文件
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 echo "usage: $0 host user passwd" exit 1 fi |
[macg @machome ~]$ sh test.sh 23 23 test.sh: line 18: [: lt: binary operator expected |
错在哪里? 整数符号(gt,lt,eq,ne)要带"-" 改成if [ $# -lt 3 ] ;then |
用简化 if 和$1,$2,$3来检测参数,不合理就调用help
[ -z "$1" ] && help 如果第一个参数不存在(-z 字符串长度为0 )
[ "$1" = "-h" ] && help 如果第一个参数是-h,就显示help