Pergunta

I need to travel through directories to certain depth(parameter2, default = 3) starting in a certain dir(parameter1). If i stumble upon a file i also need to print the depth of the file from the starting point. I'm doing this with recursion but i don't know how to stop looking at certain depth and how to print it

my code so far:

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
}

If possible without "find" please

Foi útil?

Solução

Just pass current depth as a parameter:

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
}

You can also use find with -maxdepth option:

Write a file print_depth.sh which contains:

input=$1
slashes=$(echo $input | awk -F/ '{print NF}')
echo $input $((slashes-1))

Then simply do:

 chmod +x print_depth.sh
 find . -maxdepth 3 -exec ./print_depth.sh {} \;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top