for 变量 in 列表
do command1 command2 ... commandN done
示例:
#!/bin/bash/ for value in 1 2 3 4 5 do echo "The value is $value" done
输出:
The value is 1 The value is 2 The value is 3 The value is 4 The value is 5
顺序输出字符串中的字符:
for str in 'This is a string' do echo $str done
运行结果:
This is a string
遍历目录下的文件:
#!/bin/bash for FILE in * do echo $FILE done
上面的代码将遍历当前目录下所有的文件。在Linux下,可以改为其他目录试试。
遍历文件内容:
city.txt
beijing tianjin shanghai #!/bin/bash citys=`cat city.txt` for city in $citys echo $city done
输出:
beijing
tianjin
shanghai
while循环
只要while后面的条件满足,就一直执行do里面的代码块。
其格式为:
while command
do
Statement(s) to be executed if command is true
done
命令执行完毕,控制返回循环顶部,从头开始直至测试条件为假。
示例:
#!/bin/bash c=0; while [ $c -lt 3 ] do echo "Value c is $c" c=`expr $c + 1` done
输出:
Value c is 0
Value c is 1
Value c is 2
这里由于shell本身不支持算数运算,所以使用expr命令进行自增。
until循环
until 循环执行一系列命令直至条件为 true 时停止。until 循环与 while 循环在处理方式上刚好相反。一般while循环优于until循环,但在某些时候,也只是极少数情况下,until 循环更加有用。
将上面while循环的例子改改,就能达到一样的效果:
#!/bin/bash c=0; until [ $c -eq 3 ] do echo "Value c is $c" c=`expr $c + 1` done
首先do里面的语句块一直在运行,直到满足了until的条件就停止。
输出:
Value c is 0
Value c is 1
Value c is 2
跳出循环
在循环过程中,有时候需要在未达到循环结束条件时强制跳出循环,像大多数编程语言一样,Shell也使用 break 和 continue 来跳出循环。
break
break命令允许跳出所有循环(终止执行后面的所有循环)。
#!/bin/bash i=0 while [ $i -lt 5 ] do i=`expr $i + 1` if [ $i == 3 ] then break fi echo -e $i done
运行结果:
1
2
在嵌套循环中,break 命令后面还可以跟一个整数,表示跳出第几层循环。例如:
break n
表示跳出第 n 层循环。
continue
continue命令与break命令类似,只有一点差别,它不会跳出所有循环,仅仅跳出当前循环。
#!/bin/bash i=0 while [ $i -lt 5 ] do i=`expr $i + 1` if [ $i == 3 ] then continue fi echo -e $i done










