我读了很多关于如何遍历目录的子文件夹的答案,但我看到它们都只用于循环一个级别或两个级别。是否可以遍历文件夹的所有子目录?考虑一个目录,比如说dir1。在dir1中有dir2和dir3。在dir2中有dir4 in和dir3中有dir5。在dir4中有dir6和dir7,在dir5中有dir8和dir9等等,让我们考虑“无限子文件夹”。有没有办法循环遍历dir1的所有级别?
答案 0 :(得分:0)
使用递归函数
function run_path {
# by default current dir
local current=${1:-.}
local subdir
# removing trailing / if any
current=${current%/}
# do something
echo "$current"
for subdir in "$current"/*/; do
# filtering non-existing file for example '*' not expanded
[[ ! -e $subdir ]] && continue;
# recursive call
run_path "$subdir"
done
}
run_path "<<path_to_run>>"
包含“隐藏”文件夹的另一个版本(以。开头。) 在这种情况下 。和......必须排除在外 此外,不处理符号链接,可以将其排除以避免循环。
function run_path {
# by default current dir
local current=${1:-.}
local subdir
# removing trailing / if any
current=${current%/}
# do something
echo "$current"
for subdir in "$current"/*/ "$current"/.*/; do
# filtering non-existing file for example '*' not expanded
[[ ! -e $subdir || $subdir = */../ || $subdir = */./ ]] && continue;
# recursive call
run_path "$subdir"
done
}