inputyour choice:
y
test.sh:line 3: test: y: integer expression_r_r_r expected
期望整数形式,即-eq不支持字符串
=放在别的地方是赋值,放在if[ ] 里就是字符串等于,shell里面没有==的,那是c语言的等于
无空格的字符串,可以加"",也可以不加
[macg@machome~]$ vi test.sh
echo"input a:"
read a
echo"input is $a"
if [$a = 123 ] ; then
echoequal123
fi
[macg@machome~]$ sh test.sh
inputa:
123
inputis 123
equal123
=作为等于时,其两边都必须加空格,否则失效
等号也是操作符,必须和其他变量,关键字,用空格格开(等号做赋值号时正好相反,两边不能有空格)
[macg@machome~]$ vi test.sh
echo"input your choice:"
readvar
if [$var="yes" ]
then
echo$var
echo"input is correct"
else
echo$var
echo"input error"
fi
[macg@machome~]$ vi test.sh
echo"input your choice:"
readvar
if [$var = "yes" ] 在等号两边加空格
then
echo$var
echo"input is correct"
else
echo$var
echo"input error"
fi
[macg@machome~]$ sh test.sh
inputyour choice:
y
y
inputis correct
[macg@machome~]$ sh test.sh
inputyour choice:
n
n
inputis correct
输错了也走then,都走then,为什么?
因为if把$var="yes"连读成一个变量,而此变量为空,返回1,则走else [macg@machome ~]$ sh test.sh
inputyour choice:
y
y
inputerror
[macg@machome~]$ sh test.sh
inputyour choice:
no
no
inputerror
一切正常
If [ $ANS ] 等价于 if[ -n $ANS ]
如果字符串变量非空(then), 空(else)
echo"input your choice:"
readANS
if [$ANS ]
then
echono empty
else
echoempth
fi
[macg@machome~]$ sh test.sh
inputyour choice: 回车
empth 说明“回车”就是空串
[macg@machome~]$ sh test.sh
inputyour choice:
34
noempty
整数条件表达式,大于,小于,shell里没有>和<,会被当作尖括号,只有-ge,-gt,-le,lt
[macg@machome~]$ vi test.sh
echo"input a:"
read a
if [$a -ge 100 ] ; then
echo3bit
else
echo2bit
fi
[macg@machome~]$ sh test.sh
inputa:
123
3bit
[macg@machome~]$ sh test.sh
inputa:
20
2bit
整数操作符号-ge,-gt,-le,-lt,别忘了加-
if test $a ge 100 ; then
[macg@machome~]$ sh test.sh
test.sh:line 4: test: ge: binary operator expected
if test $a -ge 100 ; then
[macg@machome~]$ sh test.sh
inputa:
123
3bit
逻辑表达式
逻辑非 ! 条件表达式的相反
if [ !表达式 ]
if [ !-d $num ] 如果不存在目录$num
逻辑与 –a 条件表达式的并列










