Bash 中的 until 循环详解

循环是编程语言的基本概念之一。当你想要一遍又一遍地运行一系列命令直到达到某个条件后终止退出时,循环很方便。

在诸如 Bash 之类的脚本语言中,循环对于自动执行重复性任务非常有用。在 Bash 脚本中有3个基本的循环结构,for 循环, while 循环,until 循环。

教程解释了 Bash 中的 until 循环的基础知识

Bash until 循环

until 循环用于当给定条件的计算结果为 false 时,重复执行给定的一组命令。

Bash until 循环采用以下形式

until [CONDITION]  do    [COMMANDS]  done

在执行命令之前计算条件。如果条件的计算结果为 false ,则执行命令。否则,如果条件的计算结果为 true ,则循环将终止,程序控制将传递给后面的命令。

在下面的示例中,在每次迭代时,循环打印变量的当前值并将变量 counter 递增 1。

#!/bin/bash    counter=0    until [ $counter -gt 5 ]  do    echo Counter: $counter    ((counter++))  done

只要 counter 变量的值大于 5 ,循环就会终止迭代。该脚本将生成以下输出:

Counter: 0  Counter: 1  Counter: 2  Counter: 3  Counter: 4  Counter: 5

Bash until 循环示例

如果您的 git 主机会有停机时间则以下的脚本可能非常有用,您可以运行该脚本一次,代替你手动键入 git pull 多次,直到主机处于联机状态。它将尝试拉出存储库,直到它成功拉出。

#!/bin/bash    until git pull &> /dev/null  do      echo "Waiting for the git host ..."      sleep 1  done    echo -e "nThe git repository is pulled."

该脚本将打印 “Waiting for the git host …” 并睡眠一秒钟直到 git 主机上线。一旦存储库被拉出,它将打印“git存储库被拉动。”。

Waiting for the git host ...  Waiting for the git host ...  Waiting for the git host ...    The git repository is pulled.

结论

while 和 until 循环非常相似,只要 while 循环迭代,只要条件求值为,true并且 until 循环迭代,只要条件求值为false。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

栗子博客 软件 Bash 中的 until 循环详解 https://www.lizi.tw/soft/15457.html

建筑工地上施工员,闲暇时弄个博客打发时间,

常见问题
  • 1、杰齐1.7仅适用于PHP5.2 2、需Zend支持 3、尽量使用宝塔面板 4、尽量使用Windows 系统,关关对Linux支持不太友好。
查看详情

相关文章

评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务

Bash 中的 until 循环详解-海报

分享本文封面