循环语句:
Bash Shell中主要提供了三种循环方式:for、while和until。
for循环声明格式:
| 代码如下 | 复制代码 |
| for variable in word_list do command done |
|
见如下示例脚本:
| 代码如下 | 复制代码 |
| /> cat > test7.sh for score in math english physics chemist #for将循环读取in后面的单词列表,类似于Java的for-each。 do echo "score = $score" done echo "out of for loop" CTRL+D /> . ./test7.sh score = math score = english score = physics score = chemist out of for loop /> cat > mylist #构造数据文件 tom patty ann jake CTRL+D /> cat > test8.sh #!/bin/sh for person in $(cat mylist) #for将循环读取cat mylist命令的执行结果。 do echo "person = $person" done echo "out of for loop." CTRL+D /> . ./test8.sh person = tom person = patty person = ann person = jake out of for loop. /> cat > test9.sh for file in test[1-8].sh #for将读取test1-test8,后缀为.sh的文件 do if [ -f $file ] #判断文件在当前目录是否存在。 then echo "$file exists." fi done CTRL+D /> . ./test9.sh test2.sh exists. test3.sh exists. test4.sh exists. test5.sh exists. test6.sh exists. test7.sh exists. test8.sh exists. /> cat > test10.sh for name in $* #读取脚本的命令行参数数组,还可以写成for name的简化形式。 do echo "Hi, $name" done CTRL+D /> . ./test10.sh stephen ann Hi, stephen Hi, ann |
|
while循环声明格式:
| 代码如下 | 复制代码 |
| while command #如果command命令的执行结果为0,或条件判断为真时,执行循环体内的命令。 do command done |
|
见如下示例脚本:
| 代码如下 | 复制代码 |
| /> cat > test1.sh num=0 while (( num < 10 )) #等同于 [ $num -lt 10 ] do echo -n "$num " let num+=1 done echo -e "nHere's out of loop." CTRL+D /> . ./test1.sh 0 1 2 3 4 5 6 7 8 9 Here's out of loop. /> cat > test2.sh go=start echo Type q to quit. while [[ -n $go ]] #等同于[ -n "$go" ],如使用该风格,$go需要被双引号括起。 do echo -n How are you. read word if [[ $word == [Qq] ]] #等同于[ "$word" = Q -o "$word" = q ] then echo Bye. go= #将go变量的值置空。 fi done CTRL+D /> . ./test2.sh How are you. Hi How are you. q Bye. |
|
until循环声明格式:
until command #其判断条件和while正好相反,即command返回非0,或条件为假时执行循环体内的命令。
do
command
done
见如下示例脚本:
/> cat > test3.sh
until who | grep stephen #循环体内的命令将被执行,直到stephen登录,即grep命令的返回值为0时才退出循环。
| 代码如下 | 复制代码 |
| do sleep 1 echo "Stephen still doesn't login." done CTRL+D |
|
孢子2生物进化中文版(Spores)
孢子2生物进化中文版让我们来做一回疯狂的博士,打造一个属于自
叫我万岁爷九游官方版
叫我万岁爷带你体验当换地点感觉,全新的模拟手游大作让你开始一
梦回凤歌
梦回凤歌手游中你将步入古代的宫廷纷争之中,本想度过美好幸福的
洋果子店rose最新版本
洋果子店最新版是一款十分容易让人垂涎的开店经营类手游。游戏玩
明日大亨最新版
明日大亨手游,一个非常经典有趣的模拟经营类型的商战手游,在游