循环是编程语言的基本概念之一。当您想要一遍又一遍地运行一系列命令直到满足特定条件时,循环会很方便。
在 Bash 等脚本语言中,循环对于自动执行重复任务非常有用。 Bash 脚本中有 3 种基本循环结构,for loop
, while 循环
, and until
loop.
本教程解释了基础知识until
在 Bash 中循环。
Bash until
Loop #
The until
循环用于执行一组给定的命令,只要给定的条件计算结果为 false。
狂欢until
循环采用以下形式:
until [CONDITION]
do
[COMMANDS]
done
在执行命令之前评估条件。如果条件评估为 false,则执行命令。否则,如果条件评估为 true,则循环将终止,程序控制将传递给后面的命令。
在下面的示例中,在每次迭代时循环都会打印变量的当前值counter
and 增加变量
by one.
#!/bin/bash
counter=0
until [ $counter -gt 5 ]
do
echo Counter: $counter
((counter++))
done
只要counter
变量的值大于四。该脚本将产生以下输出:
Counter: 0
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5
Use the 中断和继续语句来控制循环的执行。
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."
该脚本将打印“等待 git 主机...”并且sleep持续一秒钟,直到 git 主机上线。一旦拉取存储库,它将打印“The git repository is pull.”。
Waiting for the git host ...
Waiting for the git host ...
Waiting for the git host ...
The git repository is pulled.
结论#
The while
and until
循环彼此相似。主要区别在于while
只要条件计算结果为,循环就会迭代true
和until
只要条件计算结果为,循环就会迭代false
.
如果您有任何问题或反馈,请随时发表评论。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)