Here's a bash script that displays a directory structure:
bash
#!/bin/bash
# Function to display directory structure
show_tree() {
local dir="${1:-.}"
local prefix="${2}"
local level="${3:-0}"
# Get all items in the directory
local items=()
while IFS= read -r -d '' item; do
items+=("$item")
done < <(find "$dir" -maxdepth 1 -mindepth 1 -print0 | sort -z)
local count=${#items[@]}
local i=0
for item in "${items[@]}"; do
i=$((i + 1))
local basename=$(basename "$item")
# Determine if this is the last item
if [ $i -eq $count ]; then
echo "${prefix}└── $basename"
local new_prefix="${prefix} "
else
echo "${prefix}├── $basename"
local new_prefix="${prefix}│ "
fi
# If it's a directory and we haven't reached max depth, recurse
if [ -d "$item" ] && [ $level -lt $MAX_DEPTH ]; then
show_tree "$item" "$new_prefix" $((level + 1))
fi
done
}
# Default values
MAX_DEPTH=999
TARGET_DIR="."
# Parse command line arguments
while getopts "d:h" opt; do
case $opt in
d)
MAX_DEPTH=$OPTARG
;;
h)
echo "Usage: $0 [-d depth] [directory]"
echo " -d depth Maximum depth to display (default: unlimited)"
echo " -h Show this help message"
echo " directory Directory to display (default: current directory)"
exit 0
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done
# Shift past the options
shift $((OPTIND-1))
# Get target directory if provided
if [ $# -gt 0 ]; then
TARGET_DIR="$1"
fi
# Check if directory exists
if [ ! -d "$TARGET_DIR" ]; then
echo "Error: Directory '$TARGET_DIR' does not exist" >&2
exit 1
fi
# Display the root directory
echo "$TARGET_DIR"
# Show the tree structure
show_tree "$TARGET_DIR" "" 0
Save this script to a file (e.g., dirtree.sh), make it executable, and run it:
bash
chmod +x dirtree.sh
# Show current directory structure
./dirtree.sh
# Show specific directory
./dirtree.sh /path/to/directory
# Limit depth to 2 levels
./dirtree.sh -d 2
# Show help
./dirtree.sh -h
The script displays a tree-like structure similar to the tree command, with proper ASCII art for branches. It supports limiting the depth of recursion and can display any directory you specify.
If you want a simpler version without the fancy tree characters, here's a basic alternative:
bash
#!/bin/bash
show_structure() {
local dir="${1:-.}"
local indent="${2:-}"
# List all items in the directory
for item in "$dir"/*; do
# Skip if no files match the pattern
[ -e "$item" ] || continue
# Get just the filename
local name=$(basename "$item")
# Print with indentation
echo "${indent}${name}"
# If it's a directory, recurse
if [ -d "$item" ]; then
show_structure "$item" "${indent} "
fi
done
}
# Start from current directory or specified directory
show_structure "${1:-.}"
This simpler version just uses spaces for indentation and is easier to understand but doesn't have the visual tree branches.