与其他编程语言类似,Shell支持for循环。一般格式如:
for <var> in <list> do command1 command2 ... commandN done
List(列表)是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。如:
#!/bin/bash for var in 1 2 3 4 5 6 do echo "#{var}" done
运行结果:
1 2 3 4 5 6
再如:
#!/bin/bash for str in 'this is a string" do echo "${str}" done
运行结果:
this is a string
还可以这样使用:
#!/bin/bash for file in `ls` do echo "${file}" done
运行此脚本将输出当前目录下的所有文件。