在 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 循环。


霜鱼片
446 声望331 粉丝

解读权威文档,编写易懂文章。如有恰好解答您的疑问,多谢赞赏支持~