新闻动态

shell脚本for循环实现文件和目录遍历

发布日期:2022-02-03 08:14 | 文章来源:源码之家

一个for循环实现一个目录下的文件和目录遍历,很实用

[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]# 

递归遍历

#! /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.编写代码

#!/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循环实现文件和目录遍历的文章就介绍到这了,更多相关shell文件和目录遍历内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

国外稳定服务器

版权声明:本站文章来源标注为YINGSOO的内容版权均为本站所有,欢迎引用、转载,请保持原文完整并注明来源及原文链接。禁止复制或仿造本网站,禁止在非www.yingsoo.com所属的服务器上建立镜像,否则将依法追究法律责任。本站部分内容来源于网友推荐、互联网收集整理而来,仅供学习参考,不代表本站立场,如有内容涉嫌侵权,请联系alex-e#qq.com处理。

相关文章

实时开通

自选配置、实时开通

免备案

全球线路精选!

全天候客户服务

7x24全年不间断在线

专属顾问服务

1对1客户咨询顾问

在线
客服

在线客服:7*24小时在线

客服
热线

400-630-3752
7*24小时客服服务热线

关注
微信

关注官方微信
顶部