Bash实例:详解 while 和 until 命令,用于循环执行语句

Bash实例:详解 while 和 until 命令,用于循环执行语句

游戏|数码彩彩2024-04-21 7:39:46427A+A-

Bash实例:详解 while 和 until 命令,用于循环执行语句

 

在 linux 的 Bash shell 中, while 复合命令 (compound command) 和 until 复合命令都可以用于循环执行指定的语句,直到遇到 false 为止。查看 man bash 里面对 while 和 until 的说明如下:

while list-1; do list-2; done
until list-1; do list-2; done
The while command continuously executes the list list-2 as long as the last command in the list list-1 returns an exit status of zero.

 

The until command is identical to the while command, except that the test is negated; list-2 is executed as long as the last command in list-1 returns a non-zero exit status.

 

The exit status of the while and until commands is the exit status of the last command executed in list-2, or zero if none was executed.

可以看到,while 命令先判断 list-1 语句的最后一个命令是否返回为 0,如果为 0,则执行 list-2 语句;如果不为 0,就不会执行 list-2 语句,并退出整个循环。

即,while 命令是判断为 0 时执行里面的语句。

跟 while 命令的执行条件相反,until 命令是判断不为 0 时才执行里面的语句。

注意:这里有一个比较反常的关键点,bash 是以 0 作为 true,以 1 作为 false,而大部分编程语言是以 1 作为 true,0 作为 false,要注意区分,避免搞错判断条件的执行关系。

在 bash 中,常用 test 命令、[ 命令、[[ 命令来判断条件,但是 while 命令并不限于使用这几个命令来进行判断,实际上,在 while 命令后面可以跟着任意命令,它是基于命令的返回值来进行判断,分别举例说明如下。

  • 下面的 while 循环类似于C语言的 while (--count >= 0) 语句,使用 [ 命令来判断 count 变量值是否大于 0,如果大于 0,则执行 while 循环里面的语句:
count=3
while [ $((--count)) -ge 0 ]; do 
 # do some thing
done
  • 下面的 while 循环使用 read 命令读取 filename 文件的内容,直到读完为止,read 命令在读取到 EOF 时,会返回一个非 0 值,从而退出 while 循环:
while read fileline; do
 # do some thing
done < filename
  • 下面的 while 循环使用 getopts 命令处理所有的选项参数,一直处理完、或者报错为止:
while getopts "rich" arg; do
 # do some thing with $arg
done

如果要提前跳出循环,可以使用 break 命令。查看 man bash 对 break 命令说明如下:

break [n]
Exit from within a for, while, until, or select loop.

 

If n is specified, break n levels. n must be ≥ 1. If n is greater than the number of enclosing loops, all enclosing loops are exited.

 

The return value is 0 unless n is not greater than or equal to 1.

即,break 命令可以跳出 for 循环、while 循环、until 循环、和 select 循环。

点击这里复制本文地址 版权声明:本文内容由网友提供,该文观点仅代表作者本人。本站(https://www.angyang.net.cn)仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件举报,一经查实,本站将立刻删除。

昂扬百科 © All Rights Reserved.  渝ICP备2023000803号-3网赚杂谈