針對shell的控制結構,也就是shell編程時所需要的三種控制流程,順序/分支和循環。
在bash中,順序可由簡單的輸入輸出命令組成;分支語句由if、case實現;循環語句用for、while和until來實現。
一、if語句
1、基本的if語句
語句格式:
if condition
then
satements
else
statements
fi
輸出結果:
2、elif語句
elif語句格式:
if condition1
then
statements
elif condition2
then
statements
elif condition3
then
statements
……
else
statements
fi
輸出結果:
3、if語句其他形式
①if語句嵌套形式:
if condition ; then
if condition ; then
if condition ; then
statements
fi
fi
fi
②elif格式修改后:
if condition1 ; then
statements
elif condition2 ; then ??????? statements
elif condition3 ; then ??????? statements
……
else
statements
fi
輸出結果:
二、case語句
case是一個多分支結構,根據變量與各模式的匹配確定執行相應的語句序列。
case語句格式:
case variable in
pattern1) statements;;
pattern2) statements;;
pattern3) statements;;
……
patternn) statements;;
×) statements;;
esac
(1)簡單的case腳本編寫:
輸出結果:
(2)case的合并匹配模式,即在每一個模式中,還可以使用通配符和邏輯符號
輸出結果:
(3)在case中,每個分支還可以執行多條命令:
輸出結果:
三、for語句
for語句的語法格式:
for variable in values
do
statements
done
(1)簡單的for腳本
輸出結果:
(2)在for循環中使用通配符
輸出結果:
四、while語句
while語句格式:
while condition
do
statements
done
簡單的while判斷
輸出結果:
五、until語句
until語法格式:
until condition
do
statements
done
輸出結果:
六、break語句
break命令
break命令的功能是在控制條件為滿足之前,跳出for、while或until循環。可以用break命令提供一個額外的數值參數來表明所要提跳出的循環層數,但一般情況下并不建議這么做,因為它將大大降低程序的可讀性。
編寫一個break腳本跳出if循環:
輸出結果: