繁体   English   中英

如何修复此 Bash 函数以从指定路径开始并递归列出其子目录和这些子目录等

[英]How can I fix this Bash function to start at a specified path and recursively list its subdirectories and the subdirectories of those etc

我正在尝试编写一个脚本来搜索目录及其子目录等以查找与给定正则表达式匹配的文件。 所以我开始尝试编写一个函数来首先获取目录和子目录。 出于某种原因,它目前似乎只获取指定目录中的第一个子目录。

这是函数:

getDirs() {

cd "$1"
for i in *; do
    if [ -d "$i" ]; then
        echo "dir: $PWD/$i"
        getDirs "$i"
    fi
done
}

getDirs $path

任何想法如何解决这一问题?

如果您需要正则表达式来搜索文件名,请尝试使用执行此操作:

regex="YourRegexPattern"
find "$1" -type f -regextype posix-egrep -regex "$regex"

如果您想获取所有目录/子目录:

find . -type d

这应该可以做到,尽管find更有效。

getDirs() {
    for i in "$1"/*; do
        if [ -d "$i" ]; then
            echo "$i"
            getDirs "$i"
        fi
    done
}

当然,那只是因为您在循环后永远不会回到上一个目录。 你可以把所有东西都放在一个子shell中:

getDirs() {
    (
    cd "$1"
    for i in *; do
        if [[ -d "$i" ]]; then
            echo "dir: $PWD/$i"
            getDirs "$i"
        fi
    done
    )
}

getDirs $path

或者在循环后将当前目录保存到cd到它,因此:

getDirs() {
    local currentdir=$PWD
    cd "$1"
    for i in *; do
        if [[ -d "$i" ]]; then
            echo "dir: $PWD/$i"
            getDirs "$i"
        fi
    done
    cd "$currentdir"
}

getDirs $path

或者其他......我想你现在知道你的错误在哪里了!

您还应该检查您的cd是否可以使用,例如cd "$1" || <do something as the cd failed> cd "$1" || <do something as the cd failed>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM