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:

declare -i dirdepth=0;
function listfiles {
        cd "$1";
        for file in *
                for ((i=0; $i < $dirdepth; i++))
                        ##Tab between each level
                        printf "\t";
                ## Print directories with brackets ([directory])
                if [ -d "$file" ]
                        printf "\1[$file]\n";
                        printf "$file\e[0m\n";

                ##Work our way thru the system recursively
                if [ -d "$file" ]
                        listfiles "$file";
                        cd ..;
        ##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 '' (or whatever you like)
  2. Paste the code into the file and save
  3. Make the file executable
  4. Run the file: .

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:
    echo Tree of: $pwd
    find $pwd -print | sed -e “s;$pwd;\.;g;s;[^/]*\/;|__;g;s;__|; |;g”
    #very simple script. REALLY!
    echo ‘|__end tree’

  2. line 4: syntax error near unexpected token `|’

    Copy and paste, so what’s wrong with:
    find $pwd -print | sed -e ā€œs;$pwd;\.;g;s;[^/]*\/;|__;g;s;__|; |;gā€

    • Quite often when you copy and paste from web pages some characters get translated to your own charset. This could lead to some characters look like they are correct but the underlying ASCII code is different. Try to input all the characters by hand and not via copy-paste if you experience any problems with the code

  3. Bernard PIQUET

    Bonjour ;
    It seems not working with directory with a space in the name.

    • Never noticed that but you are of course correct. I usually do not work with such systems so I’ll leave it as it is for now. If you want to post a solution you are most welcome to do so šŸ™‚

Leave a Comment

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.