1. 條件測(cè)試命令: test or [
邏輯判斷跟普通的相反,當(dāng)條件為真時(shí),返回0,否則返回1.
number=2
test $number -gt 1
echo $?
0
[ $number -gt 3 ]
echo $?
1
note: [ ] 是個(gè)命令,括號(hào)中間是參數(shù),命令和參數(shù)之間要有空格。
常見(jiàn)的測(cè)試命令:
[ -d dir ]
[-f file ]
[-z string ] String 長(zhǎng)度為0時(shí)為真
[ -n string ] String 長(zhǎng)度非0時(shí)為真
[arg1 op arg2 ] op: -eq, -ne, -lt, -gt, -ge, -le
[ expr1 -a|-o expr2 ] -a=&& -o=||
2. if/then
if [ -d tmp ] ; then
echo "tmp is a directory"
fi
這里有三條命令, if [-d tmp ] 是第一條,then是的而條,fi是第三條。兩條命令在一行上,必須用;隔開(kāi)。如果then令起一行,則不用分號(hào)。
3. && ||
shell中的&&相當(dāng)于 if..then.., ||則相當(dāng)于if not ... then...,
上面的if/then語(yǔ)句也可寫(xiě)成 [ -d tmp ] && echo "tmp is a directory"
4. case
shell的case不僅能匹配整形和字符型,還能匹配字符串和wildcard, 每條分支必須以;;結(jié)束, 不需要break語(yǔ)句跳出。
echo "input your choice:"
read choice
case $choice in
Yes|yes|y)
echo "you choose Yes";;
[N|n]*)
echo "you choose No";;
esac
posted on 2011-02-22 09:06
Aaron.Chu 閱讀(1290)
評(píng)論(0) 編輯 收藏