加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

循环使用Bash中的空目录内容

发布时间:2020-12-16 01:37:22 所属栏目:安全 来源:网络整理
导读:我正在编写一个 shell脚本,我需要在其中循环遍历目录,然后循环遍历其中的文件.所以我写了这个函数: loopdirfiles() { #loop over dirs for dir in "${PATH}"/* do for file in "${dir}"/* do echo $file done done} 问题是它在空目录上回复了类似* path / t
我正在编写一个 shell脚本,我需要在其中循环遍历目录,然后循环遍历其中的文件.所以我写了这个函数:
loopdirfiles() {
    #loop over dirs
    for dir in "${PATH}"/*
    do
        for file in "${dir}"/*
            do
                echo $file
            done
    done
}

问题是它在空目录上回复了类似* path / to / dir / **的内容.

有没有办法使用这种方法并忽略这些目录?

您可以从目录名称中删除*而不是完全忽略它:
[[ $file == *"*" ]] && file="${file/%*/}"
#this goes inside the second loop

或者,如果要忽略空目录:

[[ -d $dir && $ls -A $dir) ]] || continue
#this goes inside the first loop

其他方式:

files=$(shopt -s nullglob dotglob; echo "$dir"/*)
(( ${#files} )) || continue
#this goes inside the first loop

或者你可以打开nullglob(Etan Reisner提到)和dotglob:

shopt -s nullglob dotglob
#This goes before first loop.

From Bash Manual

nullglob

If set,Bash allows filename patterns which match no files to expand
to a null string,rather than themselves.

dotglob

If set,Bash includes filenames beginning with a ‘.’ in the results of
filename expansion.

注意:dotglob包含隐藏文件(名称开头带有.的文件)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读