在Shell(如Bash)中,`while`循环

简介: 在Shell(如Bash)中,`while`循环

在Shell(如Bash)中,while循环用于重复执行一段命令或代码块,只要给定的条件为真。以下是一个基本的while循环的结构:

while [condition]
do
    # commands to be executed repeatedly
    command1
    command2
    ...
done

或者,你也可以使用以下语法:

while condition
do
    # commands to be executed repeatedly
    command1
    command2
    ...
done

其中:

  • condition 是一个返回0(真)或非0(假)的命令或表达式。在Shell中,0表示成功或真,非0表示失败或假。
  • command1, command2, ... 是在每次循环迭代中执行的命令或代码块。

以下是一些示例:

  1. 循环直到用户输入"q"来退出:
while true
do
    read -p "Enter something (type 'q' to quit): " input
    if [ "$input" == "q" ]
    then
        break
    fi
    echo "You entered: $input"
done
  1. 计数到5:
i=1
while [ $i -le 5 ]
do
    echo "Count: $i"
    i=$((i+1))
done
  1. 使用until循环,这与while相反,它会一直执行直到条件为真:
j=10
until [ $j -lt 0 ]
do
    echo "Count down: $j"
    j=$((j-1))
done

要退出while循环,可以使用break命令。如果想要跳过当前循环迭代的剩余部分并继续下一次迭代,可以使用continue命令。

目录
相关文章
|
18天前
|
存储 运维 Shell
shell中for while until 三种循环的用法
shell编程中,有几种常见的循环结构,包括for循环、while循环和until循环,总的来说,循环shell编程中扮演着至关重要的角色,它们使得自动化任务变得更加容易,提高了效率,并且可以处理各种各样的编程需求。
shell中for while until 三种循环的用法
|
2月前
|
移动开发 Shell Linux
百度搜索:蓝易云【Shell错误:/bin/bash^M: bad interpreter: No such file or directory】
将 `your_script.sh`替换为你的脚本文件名。运行此命令后,脚本文件的换行符将被转换为Linux格式,然后就可以在Linux系统上正常执行脚本了。
33 8
|
4月前
|
Shell
在Shell脚本中,`for`循环
在Shell脚本中,`for`循环
30 2
|
4月前
|
Linux Shell Windows
4:Bash shell命令-步入Linux的现代方法
4:Bash shell命令-步入Linux的现代方法
53 0
|
17天前
|
存储 Shell Linux
【攻防世界】unseping (反序列化与Linux bash shell)
【攻防世界】unseping (反序列化与Linux bash shell)
|
2月前
|
Shell
shell脚本for循环复杂用法
shell脚本for循环复杂用法
47 5
|
2月前
|
算法 Shell Linux
Linux的shell命令——判断与循环
Linux的shell命令——判断与循环
39 1
|
3月前
|
存储 Shell
Shell编程自动化之if、for、while和函数
本文主要介绍了Shell编程自动化之if、for、while和函数,并结合实例测试。
27 3
|
4月前
|
Shell
Shell(如Bash)命令行技巧
Shell(如Bash)命令行技巧
26 2
|
4月前
|
Unix Shell iOS开发
Shell错误:/bin/bash^M: bad interpreter: No such file or directory
Shell错误:/bin/bash^M: bad interpreter: No such file or directory
43 0