循环语句:
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 |
茶杯头甜蜜终章dlc 官方手机版v1.0.0.3
下载火柴人传说暗影格斗内置菜单 最新版v3.0.1
下载荒野乱斗测试服 安卓版v61.10.3
下载荒野乱斗彩虹服 安卓版v61.10.3
下载寒霜启示录 安卓版v1.25.10
寒霜启示录是一款生存模拟游戏,不少玩家可能对于末日都有着自己
末日城堡免广告版 安卓最新版v0.7.1
末日城堡免广告版是一款非常好玩的模拟经营类游戏,内部可以不看
甜蜜人生模拟器 最新版v1.4.5
甜蜜人生模拟器是一款非常好玩的模拟恋爱手游,玩家在这里能够对
武器锻造师内置功能菜单 v10.4
武器锻造师内置菜单版是游戏的破解版本,在该版本中为玩家提供了
开放空间overfield 安卓版v1.0.5
开放空间Overfield是一款箱庭养成经营手游,让你在广阔