return to first page linux journal archive
keywordscontents

Take Command

dtree

by Phil Hughes

While Linux comes with hundreds of utilities, something you got used to on another system always seems to be missing. One program in this category is something that will display a directory hierarchy or tree.

While some file managers that run under X-Windows will do this sort of task, it is sometimes very handy to have a command-line version. While not Linux-specific, the dtree utility is such a program.

I will first explain how to use dtree, then explain how it works. If you invoke it by just entering its name it will display the directory hierarchy starting at the current directory. If you invoke it with an argument, that argument is used as the starting directory. For example, if you enter dtree /home/fyl/Cool, a tree of directories under /home/fyl/Cool will be displayed.

dtree is written in the finest old-time Unix tradition using common utilities with a short shell script to glue them together. Here is the program:

: dtree
: dtree
# print a hierarchy tree starting at
# specified directory (. default)
(cd ${1-.}; pwd)
find ${1-.} -type d -print | sort -f |
sed -e "s,^${1-.},," -e "/^$/d" -e \
"s,[^/]*/\([^/]*\)$,\`-----\1," -e "s,[^/]*/,|      ,g"

Before you panic, remember, it is only four lines plus comments. It can't be that hard to figure out. The first step is to run the program and produce some sample output. If you don't have a computer at hand-or want to see what it does before you become a believer-I have included what I get by running it in my current directory (/home/fyl/LJ).

/home/fyl/LJ
`-----Advertising 
`-----Ams
`-----Ams.old
`-----Angoss
|     `-----Orig
|     `-----Shots
`-----Artsys
`-----Buyer
`-----Caldera
`-----Employee
`-----Fms
`-----Jobs
`-----ljml.d
|      `-----src.d
|      `-----tst.d
`-----OSW
`-----Posts
`-----Presentations
|       `-----Amus
|       `-----Boston
|       `-----Cjk
|       `-----Decus
|       |        `-----Old
|       |        `-----Vancouver.96
|       `-----UW
`-----Progs
`-----Related
`-----Work
`-----Write

The first line in the output is the name of the directory dtree was run on. This line was produced by the line that begins with (cd. Breaking this line down:

Unless you are familiar with regular expressions you probably didn't follow all that. But you probably learned something and you can easily use dtree without having to understand how it works.