Bash教程

Bash While循环

Bash While 循环

在本主题中,我们演示了如何在 Bash 脚本中使用 while 循环语句。
bash while 循环 可以定义为控制流语句,只要应用的条件评估为真,它就允许重复执行给定的命令集。例如,我们可以多次运行 echo 命令,也可以只是逐行读取文本文件,然后在 Bash 中使用 while 循环处理结果。

Bash While Loop 的语法

Bash while 循环格式如下:
while [ expression ];
do
commands;
multiple commands;
done
以上语法仅在表达式包含单个条件时适用。
如果表达式中包含多个条件,则while循环的语法如下:
while [ expressions ];
do
commands;
multiple commands;
done
while 循环单行语法可以定义为:
while [ condition ]; do commands; done
while control-command; do Commands; done
'while loop' 语句的一些关键点:
在执行命令之前检查条件。 'while' 循环也能够像 for 'loop' 一样执行所有工作。 只要条件评估为真,'do' 和 'done' 之间的命令就会重复执行。 'while' 循环的参数可以是布尔表达式。

它是如何工作的

while 循环是一个受限制的进入循环。这意味着在执行 while 循环的命令之前检查条件。如果条件评估为真,则执行该条件之后的命令集。否则,循环终止,程序控制权交给 'done' 语句之后的另一个命令。

Bash While 循环示例

以下是一些bash while 循环的例子:

While Loop with Single Condition

在这个例子中,while 循环与表达式中的单个条件一起使用。这是 while 循环的基本示例,它将根据用户输入打印一系列数字:
示例
#!/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."
输出
Bash While Loop

While Loop with Multiple conditions

以下是表达式中具有多个条件的 while 循环示例:
示例
#!/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."
输出
Bash While Loop

无限While 循环

无限循环是没有结束或终止的循环。如果条件的计算结果始终为真,则会创建一个无限循环。循环将持续执行,直到使用 CTRL+C 强行停止:
示例
#!/bin/bash
#An infinite while loop
while :
do
echo "Welcome to lidihuo."
done
我们也可以将上面的脚本写成一行:
#!/bin/bash
#An infinite while loop
while :; do echo "Welcome to lidihuo."; done
输出
Bash While Loop
这里, 我们使用了总是返回 true 的内置命令(:)。我们还可以使用内置命令 true 来创建无限循环,如下所示:
示例
#!/bin/bash
#An infinite while loop
while true
do
echo "Welcome to lidihuo"
done
这个 bash 脚本也将提供与上述无限脚本相同的输出。
注意: 可以通过使用 CTRL+C 或在脚本中添加一些条件退出来终止无限循环。

While Loop with a Break Statement

break 语句可用于根据应用的条件停止循环。例如:
示例
#!/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
输出
根据脚本指定循环迭代十次。但是迭代八次后有一个条件会中断迭代并终止循环。执行脚本后将显示以下输出。
Bash While Loop

带有Continue 语句的While 循环

continue 语句可用于跳过while 循环内特定条件的迭代。
示例
#!/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."
输出
Bash While Loop

While Loop with C-Style

我们也可以在 bash 脚本中编写 while 循环,类似于 C 编程语言中的 while 循环。
<强> 示例
#!/bin/bash
#while loop example in C style
i=1
while((i <= 10))
do
echo $i
let i++
done
输出
Bash While Loop

结论

在本主题中,我们讨论了如何在 Bash 中使用 while 循环语句来执行特定任务。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4