我正在编写一个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/**的内容.
有没有办法使用这种方法并忽略这些目录?
您可以打开该nullglob选项.它会导致不匹配的globs扩展为空列表,而不是保持未展开状态.
shopt -s nullglob
Run Code Online (Sandbox Code Playgroud)
*您可以从目录名称中删除,而不是完全忽略它:
[[ $file == *"*" ]] && file="${file/%\\*/}"\n#this goes inside the second loop\nRun Code Online (Sandbox Code Playgroud)\n\n或者,如果您想忽略空目录:
\n\n[[ -d $dir && $ls -A $dir) ]] || continue\n#this goes inside the first loop\nRun Code Online (Sandbox Code Playgroud)\n\n其他方式:
\n\nfiles=$(shopt -s nullglob dotglob; echo "$dir"/*)\n(( ${#files} )) || continue\n#this goes inside the first loop\nRun Code Online (Sandbox Code Playgroud)\n\n或者你可以打开(由Etan Reisnernullglob提到)并且一起:dotglob
shopt -s nullglob dotglob\n#This goes before first loop.\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n\n空球
\n\n如果设置,Bash 允许不匹配文件的文件名模式扩展为空字符串,而不是其本身。
\n\n点球
\n\n如果设置,Bash 会在文件名扩展的结果中包含以 \xe2\x80\x98.\xe2\x80\x99 开头的文件名。
\n
注意:dotglob包括隐藏文件(.名称中以 a 开头的文件)