Bash script simulating the ‘tree’ command

When trying to get to know a new system I really like the ‘tree‘ command. It gives me a fast and nice overview of the filesystem of the application. Sometimes I work on systems that does not have this great tool available and for those occasions I made this bash script:

#!/bin/bash
olddir=$PWD;
declare -i dirdepth=0;
function listfiles {
        cd "$1";
        for file in *
        do
                for ((i=0; $i < $dirdepth; i++))
                do
                        ##Tab between each level
                        printf "\t";
                done
                ## Print directories with brackets ([directory])
                if [ -d "$file" ]
                then
                        printf "\1[$file]\n";
                else
                        printf "$file\e[0m\n";
                fi

                ##Work our way thru the system recursively
                if [ -d "$file" ]
                then
                        dirdepth=$dirdepth+1;
                        listfiles "$file";
                        cd ..;
                fi
        done
        ##Done with this directory - moving on to next file
        let dirdepth=$dirdepth-1;
}
listfiles "$1";
##Go back to where we started
cd $olddir;
unset i dirdepth;

To use the script just do the following:

  1. Create a new file called 'tree.sh' (or whatever you like)
  2. Paste the code into the file and save
  3. Make the file executable
  4. Run the file: . tree.sh

This script is tested on OSX 10.6.8, Red Hat Enterprise Linux AS release 3 (Taroon Update 9)

  1. ❓ My script works: and is significantly shorter:
    #!/bin/bash
    pwd=$(pwd)
    echo Tree of: $pwd
    find $pwd -print | sed -e “s;$pwd;\.;g;s;[^/]*\/;|__;g;s;__|; |;g”
    #very simple script. REALLY!
    echo ‘|__end tree’

Reply to Niklas ¬
Cancel reply


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">

This site uses Akismet to reduce spam. Learn how your comment data is processed.