When writing documentation or doing codebase analysis, I often like to copy/paste a clean recursive directory listing into a document so I can group and annotate them. This is particularly important with badly-organized code bases.
The option I knew about was tree
, but it generates very ugly ANSI graphics that you can turn off, but it also loses the indentation. This is awful.
Maybe there are other utilities, but I was too irked to laboriously install and trial dozens of possibilities when I knew exactly what I wanted.
Thanks to ChatGPT helping me with scripting syntax, I was able to make a bash script that does what I want. Here's Sri's Documentation-Friendly Directory Listing utility! Throw it into your ~/bin
directory as stree
, then chmod a+x ~/bin/stree
to make it executable.
if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
echo "Sri's Documentation-Friendly Directory Listing"
echo "- prints a directory tree the way I like it"
echo "- usage: stree"
echo "- usage: stree [directory] [prefix]"
exit 0
fi
stree() {
local dir="$1"
local indent="$2"
for file in "$dir"/*; do
if [ -d "$file" ]; then
echo "${indent}${file##*/}/"
stree "$file" "$indent$indent"
else
echo "${indent}${file##*/}"
fi
done
}
echo "${PWD##*/}/"
# first arg or current directory
DEFAULT_PREFIX=". ";
stree "${1:-.}" "${2:-$DEFAULT_PREFIX}"
Running the script produces a listing from the current working directory like this:
components/
. AutoComplete.css
. AutoComplete.jsx
. EdgeEditor.jsx
. d3-simplenetgraph.js
. filter/
. . FilterEnums.js
. . FilterGroup.jsx
If you don't like the style of indent, use the verbose format:
stree . " "
If you're on a Mac, you can use the pbcopy
command to redirect output to the clipboard as follows:
stree | pbcopy
Linux distributions likely have their own version that works with X (e.g. xclip
).