在本小節中,將演示如何在Bash腳本中使用while
迴圈語句。
bash while迴圈可以定義為控制流語句,只要所應用的條件為真,該語句就允許重複執行給定的命令集。例如,可以運行多次echo
命令,也可以僅逐行讀取文本檔,然後使用Bash中的while迴圈處理結果。
Bash While迴圈語法
Bash while迴圈具有以下格式:
while [ expression ];
do
commands;
multiple commands;
done
僅當運算式(expression
)包含單個條件時,以上語法才適用。
如果運算式中包含多個條件,則while
迴圈的語法如下:
while [ expressions ];
do
commands;
multiple commands;
done
while
迴圈單行語法可以定義為:
while [ condition ]; do commands; done
while control-command; do Commands; done
while迴圈語句有一些關鍵要點:
- 在執行命令之前檢查條件。
- 可以使用
while
迴圈來執行“for迴圈”的所有工作。 - 只要條件評估為真,
do
和done
之間的命令就會重複執行。 while
迴圈的參數可以是布爾運算式。
如何工作
while迴圈是一個受限的輸入迴圈,因此在執行while迴圈的命令之前要先檢查條件。如果條件評估為真,則執行該條件之後的命令集。否則,迴圈終止,並且在done
語句之後將程式控制權交給另一個命令。
While迴圈示例
以下是bash while迴圈的一些示例:
示例1. 單條件的While迴圈
在此示例中,while迴圈與運算式中的單個條件一起使用。這是while迴圈的基本示例,它將根據用戶輸入列印一系列數字。
腳本檔:while-basic.sh
#!/bin/bash
#Script to get specified numbers
read -p "Enter starting number: " snum
read -p "Enter ending number: " enum
while [[ $snum -le $enum ]];
do
echo $snum
((snum++))
done
echo "This is the sequence that you wanted."
執行上面示例代碼,得到以下結果:
示例2. 有多個條件的While迴圈
以下是在運算式中具有多個條件的while
迴圈示例。
腳本檔:while-basic2.sh
#!/bin/bash
#Script to get specified numbers
read -p "Enter starting number: " snum
read -p "Enter ending number: " enum
while [[ $snum -lt $enum || $snum == $enum ]];
do
echo $snum
((snum++))
done
echo "This is the sequence that you wanted."
執行上面示例代碼,得到以下結果:
示例3. 無限While迴圈
無限迴圈是沒有結束或終止的迴圈。如果條件始終評估為true
,則將創建一個無限迴圈。迴圈將會連續執行,直到使用CTRL + C強行停止迴圈為止。
腳本檔:while-infinite.sh
#!/bin/bash
#An infinite while loop
while :
do
echo "Welcome to zaixian."
sleep 1s
done
也可以將上述腳本寫成一行:
#!/bin/bash
#An infinite while loop
while :; do echo "Welcome to zaixian."; done
執行上面示例代碼,得到以下結果:
在這裏,我們使用了始終返回true
的內置命令(:
)。還可以使用內置命令true
來創建無限迴圈,如下所示:
#!/bin/bash
#An infinite while loop
while true
do
echo "Welcome to zaixian"
done
上面bash腳本輸出與上述無限腳本輸出的結果相同。
注意:無限迴圈可以通過使用CTRL + C或在腳本內添加一些條件退出來終止。
示例4. While迴圈與Break語句
根據所應用的條件,可以使用break
語句來停止迴圈。腳本檔:whilie-break.sh
#!/bin/bash
#While Loop Example with a Break Statement
echo "Countdown for Website Launching..."
i=10
while [ $i -ge 1 ]
do
if [ $i == 2 ]
then
echo "Mission Aborted, Some Technical Error Found."
break
fi
echo "$i"
(( i-- ))
done
根據上面腳本,將迴圈分配為迭代十次。但是在八次迭代之後存在一個條件,該條件會中斷迭代並終止迴圈。執行腳本後,顯示如下輸出。
示例5. While迴圈與Continue語句
continue
語句可用於在while迴圈內跳過特定條件的迭代。
腳本檔:while-continue.sh
#!/bin/bash
#While Loop Example with a Continue Statement
i=0
while [ $i -le 10 ]
do
((i++))
if [[ "$i" == 5 ]];
then
continue
fi
echo "Current Number : $i"
done
echo "Skipped number 5 using Continue Statement."
執行上面示例代碼,得到以下結果:
示例6. C語言樣式while迴圈
還可以在bash腳本中編寫像在C編程語言中編寫while迴圈一樣。腳本檔:while-cstyle.sh
#!/bin/bash
#While loop example in C style
i=1
while((i <= 10))
do
echo $i
let i++
done
執行上面示例代碼,得到以下結果: