for命令的基本格式为:
for var in list
do
commands
done
其中var为变量,list为要循环的每项值,commands表示在do和done之间可以使用多个命令。
现在给个简单的例子:
1 #!/bin/bash
2 #how to use for command
3 for var in yu la a ha
4 do
5 echo "we can read var is: $var"
6 done

其结果就是有序的将yu 、la、a、ha输出,for命令是以空格来区分每项的值。那么如果要输出的值刚好是一个字符串或者出现特殊字符呢?
对于出现字符串可以用“ ”将字符串括起来,特殊字符的处理是使用转意字符\进行转意。
如下:
1 #!/bin/bash
2 #how to use for command
3
4 for city in xi\`an "bei jing" "shanghai"
5 do
6 echo "the city which i love is : $city"
7 done

我们页可以结合之前的if-then-else结合for命令实现一些循环操作。
1 #!/bin/bash
2 #how to use for command
3
4 for file in /home/wuyaalan/desktop/* /mnt
5 do
6 if [ -d "$file" ]
7 then
8 echo "$file is a directory"
9 elif [ -f "$file" ]
10 then
11 echo "$file is a normal file"
12 fi
13
14 done
结果。

讲了这么多似乎上面说的和我们习惯的C里面的for循环不一样,那么shell支持类似C的for格式吗,很幸运,shell提供了类似的格式。for(( var;condition;iteration process )).还是一样注意括号两边的空格。
1 #!/bin/bash
2 #how to use for command
3
4 for (( i=0;i <= 5;i++ ))
5 do
6 echo "the result is $i"
7
8 done
