shell脚本for循环实现文件和目录遍历
本文主要介绍了shell脚本for循环实现文件和目录遍历,首先进行一个要遍历的文件夹,然后循环查看每个文件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
一个for循环实现一个目录下的文件和目录遍历,很实用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | [root@localhost shell_order] # cat test27.sh #!/bin/bash #print the directory and file for file in /home/hustyangju/ * do if [ -d "$file" ] then echo "$file is directory" elif [ -f "$file" ] then echo "$file is file" fi done [root@localhost shell_order] # ./test27.sh /home/hustyangju/array is directory /home/hustyangju/menuwindow-7 .12 is directory /home/hustyangju/menuwindow-build-desktop is directory /home/hustyangju/shell_order is directory [root@localhost shell_order] # |
递归遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #! /bin/bash read_dir(){ for file in ` ls $1` #注意此处这是两个反引号,表示运行系统命令 do if [ -d $1 "/" $ file ] #注意此处之间一定要加上空格,否则会报错 then read_dir $1 "/" $ file else echo $1 "/" $ file #在此处处理文件即可 fi done } #读取第一个参数 read_dir $1 |
补充:Shell遍历目标目录和子目录下的所有文件
1.编写代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #!/bin/bash function getdir(){ for element in ` ls $fd` do dir_or_file=$fd "/" $element if [ -d $dir_or_file ] then getdir $dir_or_file else echo $dir_or_file fi done } root_dir= "/opt/datas" getdir $root_dir |
2.参数
-e 判断对象是否存在
-d 判断对象是否存在,并且为目录
-f 判断对象是否存在,并且为常规文件
-L 判断对象是否存在,并且为符号链接
-h 判断对象是否存在,并且为软链接
-s 判断对象是否存在,并且长度不为0
-r 判断对象是否存在,并且可读
-w 判断对象是否存在,并且可写
-x 判断对象是否存在,并且可执行
-O 判断对象是否存在,并且属于当前用户
-G 判断对象是否存在,并且属于当前用户组
-nt 判断file1是否比file2新 [ "/data/file1" -nt "/data/file2" ]
-ot 判断file1是否比file2旧 [ "/data/file1" -ot "/data/file2" ]
3.测试
测试结果:打印出来了目标目录以及子目录下的所有文件
到此这篇关于shell脚本for循环实现文件和目录遍历的文章就介绍到这了
原文链接:https://blog.csdn.net/hustyangju/article/details/48286843