循环语句:
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 |
荒野乱斗国际版 (BrawlStars)最新版本v56.274
下载一波超人内置修改器菜单版 安卓版v1.0.2
下载敢达决战官方正版 安卓版v6.7.9
下载敢达决战 安卓版v6.7.9
下载继承了一座戏园子无限声望铜钱版 内置菜单最新版v1.7
继承了一座戏园子折相思版是游戏的破解版本,在该版本中为玩家提
山河半世橙光清软金手指版 无限鲜花v3.24
山河半世是一款超级好玩的橙光恋爱游戏,在游戏中玩家们需要扮演
蓬莱手游折相思版 安卓版v1.0.0
蓬莱免广告版是游戏的修改版本,在该版本中为玩家去除了广告,玩
当红影后橙光游戏破解版2025 最新版v1.0
当红影后橙光破解版是一款超级好玩的娱乐圈题材的橙光游戏,在这
忽然成了万人迷清软完结版 无限鲜花版v12.15
忽然成了万人迷破解版是一款非常好玩的男性向橙光游戏,在有一天