Display recursive directory listing in Terminal

Selecting List view in Finder displays files and folders in a recursive structure with sub folders and files appearing under their parent directories.

If you work in “Terminal”:terminal with any regularity, you know there are times when listing a directory structure in a manner similar to Finder’s List view would be handy, but there is no built in command to do so.

Before I switched to Mac OS X, I used Linux where I discovered a package called “Tree”:tree. The package consists of a single command that when passed a directory, displays a recursive tree-like listing of its content in ASCII form. The source for the package is freely available and can be downloaded and built in just a couple minutes.

Building Tree for Mac OS X

The following steps assume:

  1. Your using Mac OS X 10.6 Snow Leopard
  2. The latest “Xcode Tools”:devtools from the Snow Leopard DVD or downloaded from “Apple”:download are installed
  3. Your shell’s PATH variable includes /usr/local (if you don’t know why or how, see this Hivelogic “post”:hivelogic)
  4. You have experience running UNIX commands in Terminal

Change to or create a directory where you can download and unpack the source. I keep a ‘Projects’ folder to use for this kind of task.

cd ~/Projects/src/

Download and unpack the source code

The links and versions are current at the time of this writing. See the program “site”:tree for up to date information.
 

curl -O ftp://mama.indstate.edu/linux/tree/tree-1.5.3.tgz
tar xzvf tree-1.5.3.tgz

Now change to the source directory:

cd tree-1.5.3/

Modify the Makefile for Mac OS X

The source ships with a file called ‘Makefile’ that contains information used by the build process to compile Tree. By default, the source builds for the Linux OS and installs to /usr. Use your favorite text editor to change the file for Mac OS X.
 

Find the line that reads:

prefix = /usr

… and change to:

prefix = /usr/local

Find and uncomment (remove the leading ‘#’) the CFLAGS and XOBJS lines in the Mac OS X section of the Makefile so it looks like this:

# Uncomment for OS X:
#CC=cc
CFLAGS=-O2 -Wall -fomit-frame-pointer -no-cpp-precomp
#LDFLAGS=
XOBJS=strverscmp.o

Compile and install

make
sudo make install

Assuming you did not receive any errors during the build process, you should be able to type the following and see a recursive listing of all the files and folders in the current directory:

tree

If you want to see directories only, try this:

tree -d

That’s all there is.

[terminal]http://en.wikipedia.org/wiki/Apple_Terminal
[tree]http://mama.indstate.edu/users/ice/tree/index.html
[devtools]http://developer.apple.com/technologies/xcode.html
[download]http://developer.apple.com/devcenter/mac/index.action
[hivelogic]http://hivelogic.com/articles/using_usr_local/