- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
6.8.4 循环结构 shell提供了三种循环结构: while循环:while - do - done结构 until循环:until - do - done 结构 for循环:for - in - done结构 1、while循环 功能 while循环只要循环条件为真就进入循环体。 格式 while [ condition ] do commands done 1、while循环 例子:只要用户键入Y,循环条件为真,循环体就重复执行。键入任何非Y的字符,程序结束。 # loop_ex1 echo carryon=Y while [ “$carryon” = Y ] do echo -e “I do the job as long as you type Y:\c” read carryon done echo “Job Done!” echo exit 0 1、while循环 例子:loop_ex2 # counts from 1 - 9 using while loop and the let command echo count=1 while [ $count -lt 10 ] do echo $count let count=count+1 done echo “End!” 1、while循环 例子:计算1+2+3+…+10,并输出结果 # loop_ex3 echo i=1 sum=0 while [ $i -le 10 ] do let sum=sum+i let i=i+1 done echo “sum=$sum” 1、while循环 例子:判断给定的位置参数是否为普通文件,如果是,则显示内容;否则,显示不是文件的信息。 # loop_ex4 while [ $1 ] do if [ -f $1 ] then echo display:$1 cat $1 else echo $1 is not a file name. fi shift done 1、while循环 说明: 每执行一次shift命令,就把位置参数右移一个位置。例如: 命令 ex7 a b c d e f 原位置参数 $0 $1 $2 $3 $4 $5 $6 移位后位置参数 $0 $1 $2 $3 $4 $5 2、Until循环 功能 until循环与while循环类似,不同的是,until循环在循环条件为假时,执行循环体。 格式 until [ condition ] do commands done 2、Until循环 例子:loop_until #!/bin/bash # add from 10 to 1 result=0 num=10 until [ $num -eq 0 ] do ((result=result+num)) ((num=num-1)) done echo the result is $result. 2、Until循环 例子:查看指定用户当前是否登陆到系统,如果没有,则在他登陆时进行报告。并且循环检测。 # loop_until2 echo until who | grep $1/tmp/null do sleep 30 done echo $1 is on the system echo exit 0 3、for循环 值表方式:for - in - done结构 功能 for循环用于按制定次数执行一系列命令。 格式 for variable in list - of - values do commands done 3、for循环 例子:loop_for1 # A example program to show the for_in_done construct # echo for count in 1 2 3 do echo “in the loop for $count times” done echo exit 0 3、for循环 例子:将当前目录下所有以f打头的文件分页显示。 loop_for2 for file in f* do cat $file | pr done 3、for循环 说明: list - of – values可以是全部位置参数。且可以省略。 for variable in $* do co
文档评论(0)