Chinaunix首页 | 论坛 | 博客
  • 博客访问: 708149
  • 博文数量: 67
  • 博客积分: 994
  • 博客等级: 准尉
  • 技术积分: 1749
  • 用 户 组: 普通用户
  • 注册时间: 2011-08-03 14:10
文章分类
文章存档

2014年(11)

2013年(14)

2012年(14)

2011年(28)

分类: LINUX

2013-06-06 21:54:13

上一篇学习了如何使用if-then-else进行选择的脚本。这次使用for命令。
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


























阅读(1147) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~