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)

Comments are closed.

Niklas Tech Blog
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.