在 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 命令后面可以跟着任意命令,它是基于命令的返回值来进行判断,分别举例说明如下。
count=3 while [ $((--count)) -ge 0 ]; do # do some thing done
while read fileline; do # do some thing done < filename
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 循环。