微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在编写一个 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包含隐藏文件(名称开头带有.的文件)

原文地址:https://www.jb51.cc/bash/383541.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐