本文介绍shell流程控制中的if和case。
一、if
1、if的基本格式如下:
if condition
then
statements
elif condition
then
statements
else
statements
fi
在condtion中,可以使用test或者[],只[]需要前后有空格包围。
此外,在条件中,可以使用not(!)、and(&&)、or(||)进行条件组合,同时需要注意的是and和or操作都是短路运算,一旦确定,不执行后继判断操作。
2、实例如下:
#!/usr/bin/env bash numCompare(){ local p1=$1 local p2=$2 if [ $p1 -eq $p2 ] then echo "$p1 = $p2 is true" elif [ $p1 -gt $p2 ] then echo "$p1 > $p2 is true" else echo "$p1 < $p2 is true" fi } numCompare 1 2 numCompare 2 2 numCompare 3 2 echo ==================================================== if [ ! 1 -eq 0 ] then echo "1=0 is not true" fi echo ==================================================== if test 1 -eq 0 || test 1 -gt 0 then echo "1>=0 is true" fi echo ==================================================== if [ 1 -gt 0 ] && [ 1 -ge 1 ] then echo "1>0 and 1>-1 is true" fi echo ====================================================
输出结果:
1 < 2 is true 2 = 2 is true 3 > 2 is true ==================================================== 1=0 is not true ==================================================== 1>=0 is true ==================================================== 1>0 and 1>-1 is true ====================================================
二、case
1、case的基本结构如下
case expression in
pattern1)
statements ;;
pattern2)
statements ;;
...
esac
2、实例如下
#!/usr/bin/env bash
caseNumCompare(){ case $1 in 1) echo "input 1" ;; 2) echo "input 2" ;; *) echo "input others" ;; esac } caseNumCompare 1 caseNumCompare 2 caseNumCompare 3
运行结果如下:
input 1 input 2 input others