1

I am working on a bash script in which I have to display a directory's contents in the form of a tree. I know there are one-liners to accomplish this but I am trying to figure it out using a recursive algorithm.

Here is what I have so far:

#!/bin/bash

tree(){
    space=$2
    if [ -d $1 ]
    then
        printf "%s" $space "-----|" $1
        printf "\n"
        cd $1
        space="$space-----|"
        for a in *
        do
            tree $a $space
        done
        cd ..
    else
        printf "%s" $space "-----|" $1
        printf "\n"
    fi
}    

cd $1
for file in *
do
    space="|"
    tree $file $space
done

I have the directory "Dir" containing directories "SubDir1", "SubDir2", "SubDir3", and file "filem". "SubDir1" contains files "filea", "fileb", and "filec". "SubDir2" contains directory "SubSubDir" and files "fileg", "fileh", and "filei". Directory "SubSubDir" contains files "filed", "filee", and "filef". Directory "SubDir3" contains files "filej" "filek" and "filel".

When I enter ./dirtree Dir at the command line, the following is displayed:

|-----|SubDir1
|-----|-----|filea
|-----|-----|fileb
|-----|-----|filec
|-----|SubDir2
|-----|-----|SubSubDir
|-----|-----|-----|filed
|-----|-----|-----|filee
|-----|-----|-----|filef
|-----|-----|-----|fileg
|-----|-----|-----|fileh
|-----|-----|-----|filei
|-----|SubDir3
|-----|-----|filej
|-----|-----|filek
|-----|-----|filel
|-----|filem

This output is almost correct except that files g through i are not in the directory SubSubDir. The problem is somewhere in my spacing. I need to reset the dashes when a file is not in the previous sub directory, but I need to find a method that can do this recursively so that the number of dashes is appropriate to how deep the tree is.

Thanks for your help.

1 Answer 1

4

The only time you are "deindenting" the value of space after "indenting" it is when you return to the outer loop and set it explicitly to |. You need to do so immediately after returning from any recursive call to tree. The easiest way to do that is to localize the change to the function.

#!/bin/bash

tree () {
    local space=$2
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.