公告:魔扣目录网为广大站长提供免费收录网站服务,提交前请做好本站友链:【 网站目录:https://www.morko.net 】, 免友链快审服务(50元/站),

点击这里在线咨询客服
新站提交
  • 网站:51998
  • 待审:31
  • 小程序:12
  • 文章:1030137
  • 会员:747


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

分享到:
标签:Bash
用户无头像

网友整理

注册时间:

网站:5 个   小程序:0 个  文章:12 篇

  • 51998

    网站

  • 12

    小程序

  • 1030137

    文章

  • 747

    会员

赶快注册账号,推广您的网站吧!
最新入驻小程序

数独大挑战2018-06-03

数独一种数学游戏,玩家需要根据9

答题星2018-06-03

您可以通过答题星轻松地创建试卷

全阶人生考试2018-06-03

各种考试题,题库,初中,高中,大学四六

运动步数有氧达人2018-06-03

记录运动步数,积累氧气值。还可偷

每日养生app2018-06-03

每日养生,天天健康

体育训练成绩评定2018-06-03

通用课目体育训练成绩评定