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.