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

ler*_*p90 6 bash loops

我正在编写一个shell脚本,我需要在其中循环遍历目录,然后循环遍历其中的文件.所以我写了这个函数:

loopdirfiles() {
    #loop over dirs
    for dir in "${PATH}"/*
    do
        for file in "${dir}"/*
            do
                echo $file
            done
    done
}
Run Code Online (Sandbox Code Playgroud)

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

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

Eta*_*ner 6

您可以打开该nullglob选项.它会导致不匹配的globs扩展为空列表,而不是保持未展开状态.

shopt -s nullglob
Run Code Online (Sandbox Code Playgroud)


Jah*_*hid 2

*您可以从目录名称中删除,而不是完全忽略它:

\n\n
[[ $file == *"*" ]] && file="${file/%\\*/}"\n#this goes inside the second loop\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者,如果您想忽略空目录:

\n\n
[[ -d $dir && $ls -A $dir) ]] || continue\n#this goes inside the first loop\n
Run Code Online (Sandbox Code Playgroud)\n\n

其他方式:

\n\n
files=$(shopt -s nullglob dotglob; echo "$dir"/*)\n(( ${#files} )) || continue\n#this goes inside the first loop\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者你可以打开(由Etan Reisnernullglob提到)并且一起:dotglob

\n\n
shopt -s nullglob dotglob\n#This goes before first loop.\n
Run Code Online (Sandbox Code Playgroud)\n\n


\n来自 Bash 手册

\n\n

\n

空球

\n\n

如果设置,Bash 允许不匹配文件的文件名模式扩展为空字符串,而不是其本身。

\n\n

点球

\n\n

如果设置,Bash 会在文件名扩展的结果中包含以 \xe2\x80\x98.\xe2\x80\x99 开头的文件名。

\n
\n\n

注意:dotglob包括隐藏文件(.名称中以 a 开头的文件)

\n