if [表达式1 –a 表达式2]
逻辑或 -o 条件表达式的或
if [表达式1 –o 表达式2]
逻辑表达式
表达式与前面的= != -d –f –x -ne -eq -lt等合用
逻辑符号就正常的接其他表达式,没有任何括号(),就是并列
if [-z "$JHHOME" -a -d $HOME/$num ]
注意逻辑与-a与逻辑或-o很容易和其他字符串或文件的运算符号搞混了
最常见的赋值形式,赋值前对=两边的变量都进行评测
左边测变量是否为空,右边测目录(值)是否存在(值是否有效)
[macg@mac-home~]$ vi test.sh
:
echo"input the num:"
readnum
echo"input is $num"
if [-z "$JHHOME" -a -d $HOME/$num ] 如果变量$JHHOME为空,且$HOME/$num目录存在
then
JHHOME=$HOME/$num 则赋值
fi
echo"JHHOME is $JHHOME"
-----------------------
[macg@mac-home~]$ sh test.sh
inputthe num:
ppp
inputis ppp
JHHOMEis
目录-d$HOME/$num 不存在,所以$JHHOME没被then赋值
[macg@mac-home~]$ mkdir ppp
[macg@mac-home~]$ sh test.sh
inputthe num:
ppp
inputis ppp
JHHOMEis /home/macg/ppp
一个-o的例子,其中却揭示了”=”必须两边留空格的问题
echo"input your choice:"
readANS
if[ $ANS="Yes" -o $ANS="yes" -o $ANS="y"-o $ANS="Y" ]
then
ANS="y"
else
ANS="n"
fi
echo$ANS
[macg@machome~]$ sh test.sh
inputyour choice:
n
y
[macg@machome~]$ sh test.sh
inputyour choice:
no
y
为什么输入不是yes,结果仍是y(走then)
因为=被连读了,成了变量$ANS="Yes",而变量又为空,所以走else了
[macg@machome~]$ vi test.sh
echo"input your choice:"
readANS echo "input your choice:"
readANS
if[ $ANS = "Yes" -o $ANS = "yes" -o $ANS = "y"-o $ANS = "Y" ]
then
ANS="y"
else
ANS="n"
fi
echo$ANS
[macg@machome~]$ sh test.sh
inputyour choice:
no
n
[macg@machome~]$ sh test.sh
inputyour choice:
yes
y
[macg@machome~]$ sh test.sh
inputyour choice:
y
y
以 test条件表达式作为if条件
iftest $num -eq 0 等价于 if[ $num –eq 0 ]
test 表达式,没有 [ ]
iftest $num -eq 0
then
echo"try again"
else
echo"good"
fi
mantest
[macg@machome~]$ man test
[(1) User Commands [(1)
SYNOPSIS
testEXPRESSION
[EXPRESSION ]
[-n]STRING
thelength of STRING is nonzero -n和直接$str都是非0条件
-zSTRING
thelength of STRING is zero
STRING1= STRING2
thestrings are equal
STRING1!= STRING2
thestrings are not equal
INTEGER1-eq INTEGER2
INTEGER1is equal to INTEGER2
INTEGER1-ge INTEGER2
INTEGER1is greater than or equal to INTEGER2
INTEGER1-gt INTEGER2
INTEGER1is greater than INTEGER2










