UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 16.18 Listing Files You've Created/Edited Today Chapter 16
Where Did I Put That?
Next: 16.20 The vtree Visual Directory Tree Programs
 

16.19 stree: Simple Directory Tree

Here's a simple script that prints a directory tree. It works on any terminal, can be printed or sent in a mail message, and so on. If you don't give stree a directory name, it starts at the current directory. If you give it a -a (all) option, the stree script lists all files, directories, symbolic links, etc. Otherwise, it just lists directories. For example:

% stree lib
Tree for directory lib:

lib
 "      at_cron
 "       "      RCS
 "       "      test
 "      csh
 "      ksh
 "      RCS.Z
 "      tmac
 "       "      mm
 "       "       "      RCS
 "       "      ms
 "       "       "      RCS

The top-level directory is listed along the left-hand edge. The first level of subdirectories is indented by one tabstop. A ditto mark (") below a name means "same parent directory as above." So, for example, the last directory in that listing is lib/tmac/ms/RCS.

Here's the script:



${1-.} 








"newline 



@ 
#! /bin/sh

case "$1" in
-a) shift
    dir=${1-.}  # DEFAULT TO CURRENT DIRECTORY
    echo Tree for directory $dir and its files:
    ;;
*)  findtype="-type d"  # IF NO -a FLAG, MAKE find USE "-type d"
    dir=${1-.}
    echo Tree for directory $dir:
    ;;
esac

echo "
$dir"
find $dir $findtype -print |
tr / \\001 | sort -f | tr \\001 / |
sed -e s@\^$dir@@ -e /\^$/d -e 's@[^/]*/@ "[TAB]@g'

The script uses tr (35.11) to change slash (/) characters into CTRL-a (octal 001 (51.3)) during the sort. That makes the slashes sort before letters and other characters so the directory names will always come out before their contents.

- JP


Previous: 16.18 Listing Files You've Created/Edited Today UNIX Power ToolsNext: 16.20 The vtree Visual Directory Tree Programs
16.18 Listing Files You've Created/Edited Today Book Index16.20 The vtree Visual Directory Tree Programs

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System