shell文件和目录遍历

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

shell文件和目录遍历

hustyangju   2022-05-24 我要评论

一个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.测试

测试结果:打印出来了目标目录以及子目录下的所有文件

 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们