循环使用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包含隐藏文件(名称开头带有.的文件)

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...