在 Linux 的 Bash shell 中,while
复合命令 (compound command) 和 until
复合命令均可以用于循环执行指定的语句,直到遇到 false 为止。查看 man bash 里面对 while 和 until 的说明以下:shell
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
注意:这里有一个比较反常的关键点,bash 是以 0 做为 true,以 1 做为 false,而大部分编程语言是以 1 做为 true,0 做为 false,要注意区分,避免搞错判断条件的执行关系。less
在 bash 中,使用 test
命令、[
命令来做为判断条件,可是 while
命令并不限于使用这两个命令来进行判断,实际上,在 while
命令后面能够跟着任意命令,它是基于命令的返回值来进行判断,分别举例以下。编程语言
下面的 while 循环相似于C语言的 while (--count >= 0) 语句,使用 [
命令来判断 count 变量值是否大于 0,若是大于 0,则执行 while 循环里面的语句:ide
count=3 while [ $((--count)) -ge 0 ]; do # do some thing done
下面的 while 循环使用 read
命令读取 filename 文件的内容,直到读完为止,read
命令在读取到 EOF 时,会返回一个非 0 值,从而退出 while 循环:oop
while read fileline; do # do some thing done < filename
下面的 while 循环使用 getopts
命令处理全部的选项参数,一直处理完、或者报错为止:code
while getopts "rich" arg; do # do some thing with $arg done
若是要提早跳出循环,能够使用 break
命令。查看 man bash 对 break
命令说明以下:ci
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 循环。get