手机版
你好,游客 登录 注册
背景:
阅读新闻

bash 脚本编程六 循环,遍历目录

[日期:2012-09-17] 来源:Linux社区  作者:sheismylife [字体:大 中 小]

现在看看循环的写法:

  1. for v in ...  
  2. do   
  3. ...  
  4. done  
写个简单的例子看一下:
  1. #!/bin/bash  
  2. for v in man woman child  
  3. do  
  4.     echo $v  
  5. done  
输出结果为:
  1. $ ./test.sh  
  2. man  
  3. woman  
  4. child  
for in的写法和很多现代语言相近。

就是...可以用 空格隔开的若干个值表示


再进一步,打开一个目录,遍历其中的文件(不递归)

  1. #!/bin/bash  
  2. cd ~/Downloads  
  3. for f in *.jpg  
  4. do  
  5.     echo $f  
  6. done  
运行结果:
  1.  ./test.sh  
  2. 08_avatar_middle.jpg  
  3. 84e_4ffbfce3_9ab8_d9c2_b577_acbfc7edbfc2_1.jpg  
  4. DSCN0743.jpg  
  5. IMAG0611.jpg  
  6. IMG_20120423_135302 (1).jpg  
  7. IMG_20120423_135302.jpg  
  8. IMG_20120423_144215 (1).jpg  
  9. IMG_20120423_144215.jpg  
  10. psb.jpg  
  11. ssh2-300x259.jpg  
这是一个很简单的遍历当前目录的文件的方法。

如果加上目录路径也行。不一定非要切换当前目录。

下面这个例子添加了检测目录是否存在的逻辑:

  1. #!/bin/bash  
  2. if [ -d ~/Downloads ]  
  3. then  
  4.     echo '~/Downloads folder exists'  
  5. else  
  6.     echo "~/Downloads folder doesn't exist"  
  7.     exit  
  8. fi  
  9.   
  10. for f in ~/Downloads/*.jpg  
  11. do  
  12.     echo $f  
  13. done  
~ 可以用 $HOME来替代。

注意,如果要防止换行,可以用双引号去掉里面包含的换行符。

  1. #!/bin/bash  
  2. if [ -d $HOME/Downloads ]  
  3. then  
  4.     echo '~/Downloads folder exists'  
  5. else  
  6.     echo "~/Downloads folder doesn't exist"  
  7.     exit  
  8. fi  
  9.   
  10. for f in "$HOME/Downloads/*.jpg"  
  11. do  
  12.     echo $f  
  13. done  

注意f in 后面 多了双引号。显示的结果就变了:

  1.  ./test.sh  
  2. ~/Downloads folder exists  
  3. /home/chenshu/Downloads/08_avatar_middle.jpg /home/chenshu/Downloads/84e_4ffbfce3_9ab8_d9c2_b577_acbfc7edbfc2_1.jpg /home/chenshu/Downloads/DSCN0743.jpg /home/chenshu/Downloads/IMAG0611.jpg /home/chenshu/Downloads/IMG_20120423_135302 (1).jpg /home/chenshu/Downloads/IMG_20120423_135302.jpg /home/chenshu/Downloads/IMG_20120423_144215 (1).jpg /home/chenshu/Downloads/IMG_20120423_144215.jpg /home/chenshu/Downloads/psb.jpg /home/chenshu/Downloads/ssh2-300x259.jpg  

如果想要一个变量递增,可以这样写:

  1. #!/bin/bash  
  2. i=0  
  3. while [ $i -lt 5 ]  
  4. do  
  5.     echo $i  
  6.     let i++  
  7. done  
这里用了while循环,显示结果:
  1. $ ./test.sh  
  2. 0  
  3. 1  
  4. 2  
  5. 3  
  6. 4  
linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款