if then else fi |
If语句忘了结尾fi test.sh: line 14: syntax error: unexpected end of fi |
if command then if then | 执行失败,返回非0 (grep,没找到匹配) |
if [ expression_r_r_r then | |
if test expression_r_r_r then | |
[ -f "/etc/shadow" ] && echo "This computer uses shadow passwors" |
|
| |
0为真,走then | |
必须:if [ i –ne 0 ] 但支持字符串变量直接if if [ str ] 如果字符串非0 | if (i ) |
=================================以command作为if 条件===================================
echo –n “input:” read user if 多条指令,这些命令之间相当于“and”(与) grep $user /etc/passwd >/tmp/null who -u | grep $user then else fi |
# sh test.sh input : macg macg macg has logged # sh test.sh input : ddd ddd has not logged |
if 以函数作为if条件, getyn then echo " your answer is yes" else echo "your anser is no" fi |
$ vi testsh.sh #!/bin/sh if cat 111-tmp.txt | grep ting1 then echo found else echo "no found" fi | #!/bin/sh cat 111-tmp.txt | grep ting1 if [ $? -eq 0 ] then echo $? echo found else echo $? echo "no found" fi |
$ sh testsh.sh no found | $ sh testsh.sh 1 no found |
$ vi 111-tmp.txt that is 222file thisting1 is 111file $ sh testsh.sh thisting1 is 111file found | $ vi 111-tmp.txt that is 222file thisting1 is 111file $ sh testsh.sh thisting1 is 111file 0 found |
========================================以条件表达式作为 if条件=============================
if [ 条件表达式 ]
then
else
fi
- 文件表达式
if [ -d ...
if [ -s file
if [ -r file
if [ -w file
if [ -x file
- 整数变量表达式
if [ int1 -ne int2 ]
if [ int1 -ge int2 ]
if [ int1 -gt int2 ]
if [ int1 -le int2 ]
if [ int1 -lt int2 ]
-
字符串变量表达式
if
if
if
if
if [ a = b ] ;then echo equal else echo no equal fi |
[macg@machome ~]$ sh test.sh input a: 5 input b: 5 no equal |
if [ $a = $b ] ;then echo equal else echo no equal fi |
[macg@machome ~]$ sh test.sh input a: 5 input b: 5 equal |
[macg@machome ~]$ vi test.sh echo -n "input your choice:" read var if then echo $var fi [macg@machome ~]$ sh -x test.sh input your choice: y test.sh: line 3: test: y: integer expression_r_r_r expected |