0

I have wrote the following script:

  #!/bin/bash

if [ $# -eq 0 ]
then
    read current_dir
else
    current_dir=$1
fi

function print_tree_representation ()
{
    for file in `ls -A $1`
    do
        local times_p=$2
        while [ $times_p -gt 0 ]
        do
            echo -n "----"
            times_p=$(( $times_p - 1 ))
        done
        echo $file

        if test -d $file
        then
            local new_path=$1/$file
            local new_depth=$(( $2 + 1 ))

            print_tree_representation $new_path $new_depth        
        fi
    done
}

print_tree_representation $current_dir 0

for printing the tree-like structure of the directory passed as argument. However, it doesn't go beyond the second level of depth. I can't figgure out what is wrong.

  • 1
    Did you know that there is a tree command ? Have you checked it? – Valentin Bajrami Mar 20 '16 at 11:35
  • @val0x00ff Do I need to say that this is a homework problem? – cristid9 Mar 20 '16 at 12:29
2

The problem is with this line:

if test -d $file

The $file you have extracted from ls -A doesn't contain the full path. You can fix it by replacing that line with

if test -d "$1/$file"

There's another bug, which is that it'll break all over the place if a filename has spaces in it. Put filenames in quotes.

  • Thanks. This is actually a pretty stupid mistake, that I did. – cristid9 Mar 20 '16 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.