2012年3月8日 星期四

bash 檔中的 if else判斷式

[Reference]
sites.google.com/site/tiger2000/home 
第二十四章 Shell Script 

Testing 判斷式


Testing 判斷式通常與if-then-else一起互用, 以便發揮其效果. 先從一個最簡單的例子看起 :

$ cat myscript7
#!/bin/sh
if [ -f /etc/passwd ]; then
   echo "/etc/passwd is a file"
else
   echo "PANIC : /etc/passwd is not a file!!"
fi

先說明一下 [ -f /etc/passwd ] 這個最重要的部份, [ ] 裡面就是判斷式, 而這裡是判斷 /etc/passwd 是不是一個 file ?
由結果來看看是執行 then 下面的敘述, 或者執行 else 的敘述.

同時很重要一點是 底下這些敘述都是不正確的敘述, 會有錯誤產生喔 :
[-f /etc/passwd ]  [-f 連在一起 
[ -f /etc/passwd]  passwd] 連在一起
[ -f/etc/passwd ]  -f與/etc/passwd連在一起

這裡是一個雙重條件判斷的範例:

CONFIG=config.ini
if [ -e $CONFIG -a "`grep ^Mailer $CONFIG`" ]; then
   SERVER_LIST=(`grep ^Mailer $CONFIG | cut -d= -f2 | sed 's/,/ /g'`)
   SERVER_NUM=${#SERVER_LIST[@]}
else
   echo "$CONFIG not found"
   exit 2
fi

上述的範例有些複雜, 簡單的說它透過 -a (代表 and) 判斷是否同時滿足  -e $CONFIG 與 `grep ^Mailer $CONFIG?
所以另外一個 -o (寄是代表 or) 就會類似這樣了:

if [ -e $CONFIG -o "`grep ^Mailer $CONFIG`" ]; then
   XXXXX (自己發揮)
fi


所以利用 [ ] 我們可以做出以下這些判斷, 這些也都很常用喔 !!

test     true if ....

[ string1 = string2 ] string1 and string2 are equal [ string1 != string2 ] string1 and string2 are not equal [ string1 \< string2 ] string1 is lexically less than string2 (e.g. 'a' is less than 'b') [ string1 \> string2 ] string1 is lexically greater than string2 (e.g. 'b' is greater than 'a') [ -z string ] string is zero (e.g. a empty string) [ -n string ] string is nonzero (e.g. a VAR string) [ -e file ] file exists [ -f file ] file is a file [ -d file ] file is a directory [ -c file ] file is a character device [ -b file ] file is a block device [ -p file ] file is a named pipe [ -s file ] file is not empty [ -k file ] file's sticky bit is set [ -S file ] file is a socket [ -L file ] file is a symbolic link [ -r file ] file is readable by user [ -w file ] file is writeable by user [ -x file ] file is executeable by user [ -O file ] file is owner by user [ -G file ] file is group owned by a greoup [ -u file ] file has its set user ID bit set [ -g file ] file has its group user ID bit set [ file1 -nt file2 ] file1 is newer than file2 [ file1 -ot file2 ] file1 is older than file2 [ file -ef file2 ] file1 is another name for file2 [ n1 -eq n2 ] true if integer n1 = integer n2 [ n1 -ne n2 ] true if integer n1 <> n2 [ n1 -gt n2 ] true if n1 > n2 [ n1 -ge n2 ] true if n1 >= n2 [ n1 -lt n2 ] true if n1 < n2 [ n1 -le n2 ] true if n1 <= n2

沒有留言:

張貼留言