如何在 Bash 中使用 While 循环
    
    Suraj Joshi
    2023年1月30日
    
    Bash
    Linux
    
- 
          
            Bash 中的 
while循环语法 - 
          
            例子:Bash 中的 
while循环 - 
          
            示例:Bash 中的无限 
while循环 - 
          
            示例:带有 
break语句的 Bash 中的 while 循环 - 
          
            示例:带有 
continue语句的 Bash 中的while循环 
while 循环几乎是所有编程语言中使用最广泛的循环结构之一。当我们不知道需要运行一个循环的次数时,就会用到它。我们可以为 while 循环指定一个条件,循环中的语句会被执行,直到条件变为假。
Bash 中的 while 循环语法
    
while [condition]
do
   command-1
   command-2
     ...
     ...
   command-n
done
这里,condition 代表每次在循环中执行命令前需要检查的条件。如果 condition 为真,我们就执行循环中的语句。如果 condition 为假,我们退出循环。从 command-1 到 command-n 的语句是在循环中执行的语句,直到 condition 变为 false。
例子:Bash 中的 while 循环
#!/bin/bash
num=5
while [ $num -ge 0 ]
do
  echo $num
  ((num--))
done
输出:
5
4
3
2
1
0
这里,最初,num 被设置为 5。只要 num 的值大于或等于 0,我们就在终端打印 num,并在循环中把 num 递减 1。
示例:Bash 中的无限 while 循环
#!/bin/bash
while true
do
  echo "This is an infinite while loop. Press CTRL + C to exit out of the loop."
  sleep 0.5
done
输出:
This is an infinite while loop. Press CTRL + C to exit out of the loop.
This is an infinite while loop. Press CTRL + C to exit out of the loop.
This is an infinite while loop. Press CTRL + C to exit out of the loop.
^C
这是一个无限循环,每 0.5 秒打印出 This is an infinite while loop. Press <kbd>Ctrl</kbd>+<kbd>C</kbd> to exit out of the loop.。要退出循环,我们可以按 CTRL+C。
示例:带有 break 语句的 Bash 中的 while 循环
#!/bin/bash
num=5
while [ $num -ge 0 ]
do
  echo $num
  ((num--))
  if [[ "$num" == '3' ]]; then
    echo "Exit out of loop due to break"
    break
  fi
done
输出:
5
4
Exit out of loop due to break
在上面的程序中,num 初始化为 5,只要 num 大于或等于 0,循环就会被执行,但由于循环中的 break 语句在 num 为 3 时,所以当 num 的值变成 3 时,我们就退出循环。
示例:带有 continue 语句的 Bash 中的 while 循环
#!/bin/bash
num=6
while [ $num -ge 1 ]
do
  ((num--))
  if [[ "$num" == '3' ]]; then
    echo "Ignore a step due to continue"
    continue
  fi
  echo $num
  
done
输出:
5
4
Ignore a step due to continue
2
1
0
在上面的程序中,num 初始化为 6,在循环中,我们首先将 num 减少 1,然后打印 num 的最新值。只要 num 值大于或等于 1,循环就会执行。当 num 变成 3 时,脚本不打印 num 的值,因为当 num 为 3 时,我们有 continue 语句。
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
作者: Suraj Joshi
    Suraj Joshi is a backend software engineer at Matrice.ai.
LinkedIn