if…then
单层if
格式:
if conditionthen语句1语句2...fi
示例:
a=3b=4if [ "$a" -lt "$b" ] && [ "$a" -gt 2 ]thenecho ${a}在范围内fi
单层if…else
命令格式:
if conditionthen语句1语句2...else语句1语句2...fi
示例:
a=3b=4if ! [ "$a" -lt "$b" ]thenecho ${a}不小于${b}elseecho ${a}小于${b}fi
多层if-elif-elif-else
格式:
if conditionthen语句1语句2...elif conditionthen语句1语句2...elif conditionthen语句1语句2else语句1语句2...fi
示例:
a=4if [ $a -eq 1 ]thenecho ${a}等于1elif [ $a -eq 2 ]thenecho ${a}等于2elif [ $a -eq 3 ]thenecho ${a}等于3elseecho 其他fi
case…esac
类似于C/C++中的switch语句。
格式:
case $变量名称 in值1)语句1语句2...;; # 类似于C/C++中的break,不能省略值2)语句1语句2...;;*) # 类似于C/C++中的default语句1语句2...;; # 可以省略,但最好别esac
示例:
a=4case $a in1)echo ${a}等于1;;2)echo ${a}等于2;;3)echo ${a}等于3;;*)echo 其他;;esac
