shell脚本之if分支
此文仅作记录,原文地址:https://blog.csdn.net/chengqiuming/article/details/78601946
一、if格式
if [ condition ] --注意括号两边有空格,condition 是个条件表达式
then
commands
fi
做用:判断 condition 条件是否成立,若是成立,执行中间的命令 commands,不成立不执行。
如: if [ $a -gt $b ]
then
echo "a大于b"
fi
if 能够接 条件表达式 (如 if [ $a -gt $b ]),也能够直接接一个命令(如 if mkdir /abc ) ,这时,会把命令的执行结果做为判断,若是成功执行,就至关于条件成立,若是执行不成功,就至关于条件不成立。
code
二、if else格式
if condition
then
command1
command2
...
commandN
else
command
fi
三、if else-if else格式
if condition1
then
command1
elif condition2
command2
else
commandN
fi
if else语句常常与test命令结合使用,以下所示:
io
num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
echo 'The two numbers are equal!'
else
echo 'The two numbers are not equal!'
fi
输出:
The two numbers are equal!
class
四、if的嵌套
格式一:
if [ condition ]
then
if [ condition ]
then
commands1
else
commands2
fi
fi
格式二:
if [ condition ]
then
if [ condition ]
then
commands1
else
commands2
fi
else
commands3
fi
五、多条件表示:
逻辑与
if [ condition1 -a condition2 ]
或 if [ condition1 ] && [ condition2 ]
逻辑或
if [ condition1 -o condition2 ]
或 if [ condition1 ] || [ condition2 ]
逻辑非(取反)
!