递归bash中的存储深度

递归bash中的存储深度,bash,recursion,depth,Bash,Recursion,Depth,我需要从某个目录(参数1)开始,遍历目录到某个深度(参数2,默认值=3)。如果我偶然发现一个文件,我还需要从起点打印文件的深度。我正在使用递归进行此操作,但我不知道如何停止查看特定深度,以及如何打印它 到目前为止,我的代码是: function tree(){ for path in "{$1}/*" if [ -d "$path"]; then printf "%5s %s" DIR $path #and also depth

我需要从某个目录(参数1)开始,遍历目录到某个深度(参数2,默认值=3)。如果我偶然发现一个文件,我还需要从起点打印文件的深度。我正在使用递归进行此操作,但我不知道如何停止查看特定深度,以及如何打印它

到目前为止,我的代码是:

function tree(){
    for path in "{$1}/*"        
        if [ -d "$path"]; then
            printf "%5s %s" DIR $path #and also depth           
            tree "$path"
        else [ -f "$path"]; then
            printf "%5s %s" File $path #and also depth              
        fi
        done
}

如果可能,没有“查找”功能,请将当前深度作为参数传递:

function tree(){
    local max_depth=$2
    if [ -n "$max_depth" ]; then
        max_depth=3
    fi
    tree_helper $1 0 $max_depth
}

function tree_helper() {
    local current_depth=$2
    local max_depth=$3
    for path in "{$1}/*"        
        if [ -d "$path"]; then
            printf "%5s %s %d" DIR $path $current_depth #and also depth           
            if [ $current_depth -lt $max_depth ]; then
                tree_helper "$path" $((current_depth+1)) $max_depth
            fi
        else [ -f "$path"]; then
            printf "%5s %s" File $path $current_depth
        fi
        done
}
您还可以将
find
-maxdepth
选项一起使用:

编写一个文件
print_depth.sh
,其中包含:

input=$1
slashes=$(echo $input | awk -F/ '{print NF}')
echo $input $((slashes-1))
然后简单地做:

 chmod +x print_depth.sh
 find . -maxdepth 3 -exec ./print_depth.sh {} \;