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.命令列參數
2.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