Generating ASCII Directory Tree Diagrams for Unix File Hierarchy Comparison in CLI Environments


6 views

When working on server systems via SSH, we often need to compare different directory structures without graphical tools. Traditional solutions like tree command or GUI tools fall short when we need:

  • Customized output focusing only on directories
  • Clean ASCII representation for terminal sharing
  • Quick comparison between similar hierarchies

The tree command provides basic ASCII output:

tree -d -L 2 /path/to/directory
.
├── config
├── logs
│   ├── archive
│   └── current
└── src
    ├── main
    └── test

For more control, combine with find:

find /path -type d -printf '%h/%f\n' | sort | awk -F'/' '{
    for (i=1; i<NF; i++) {
        printf "%4s", "|"
    }
    print "-- "$NF
}'

1. dirtree.py (Python solution):

#!/usr/bin/env python3
import os
import sys

def print_tree(startpath, prefix=''):
    dirs = [d for d in os.listdir(startpath) 
            if os.path.isdir(os.path.join(startpath, d))]
    dirs.sort()
    for i, dirname in enumerate(dirs):
        if i == len(dirs)-1:
            new_prefix = prefix + "    "
            print(f"{prefix}└── {dirname}")
        else:
            new_prefix = prefix + "│   "
            print(f"{prefix}├── {dirname}")
        print_tree(os.path.join(startpath, dirname), new_prefix)

if __name__ == "__main__":
    print_tree(sys.argv[1] if len(sys.argv) > 1 else ".")

2. Using tree with custom formatting:

tree -d -L 3 --charset=ascii --noreport /path | \
    sed 's//|/g; s/-/--/g; s/\\-/|/g'

To compare two similar directory structures side-by-side:

diff -y <(tree -d /path/to/first) <(tree -d /path/to/second) | colordiff

For persistent documentation:

tree -d -o dir_structure.txt /path
asciidoctor -b html -o dir_structure.html dir_structure.txt
  • lsd: Modern ls replacement with tree view
  • broot: Interactive tree navigation
  • nnn: File manager with tree export

Remember to install these tools in your development environment for quick directory visualization needs.


When working with Unix servers through SSH, there are frequent situations where we need to quickly visualize directory structures without GUI tools. This becomes particularly useful when:

  • Comparing similar but not identical directory hierarchies
  • Documenting project structures for team discussions
  • Troubleshooting permission or path issues

The most straightforward solution is the tree command, available in most Unix-like systems:


$ tree -d -L 2
.
├── config
├── src
│   ├── main
│   └── test
└── target

Key options:


-d    # Show directories only
-L N  # Limit depth to N levels
-I pattern # Exclude patterns
-o filename # Output to file

For systems without tree, here's a pure Bash solution:


find . -type d -print | awk -F'/' '{
    depth = NF-2;
    for(i=1; i<=depth; i++) printf "│   ";
    if (depth>0) printf "├── ";
    print $NF
}'

For more control, this Python script generates professional ASCII trees:


#!/usr/bin/env python3
import os
from pathlib import Path

def generate_tree(startpath, max_depth=None, dirs_only=False):
    prefix = {0: '', 1: '│   ', 2: '    '}
    for root, dirs, files in os.walk(startpath):
        level = root.replace(startpath, '').count(os.sep)
        if max_depth and level > max_depth: continue
        
        indent = '├── ' if level > 0 else ''
        print(prefix.get(level-1, '') + indent + os.path.basename(root))

if __name__ == '__main__':
    generate_tree('.', max_depth=2, dirs_only=True)

To compare directory structures side-by-side in columns:


paste <(tree -d dir1) <(tree -d dir2) | column -t -s $'\t'
  • Add file counts: tree -d -i -f | while read d; do echo -n "$d: "; ls "$d" | wc -l; done
  • Highlight differences: diff -y <(tree -d dir1) <(tree -d dir2)
  • Generate Markdown: tree --noreport -d -I 'node_modules|.git' | sed 's/│/ /; s/├/ /; s/└/ /'