Of course! Here is a comprehensive Bash script to display a directory structure.
This script is designed to be robust and user-friendly. It has two modes:
- Preferred Mode: If you have the
tree command installed (which is the best tool for this job), the script will use it.
- Fallback Mode: If
tree is not found, the script will use a pure Bash recursive function to draw the directory structure. This makes the script work on almost any system with Bash.
The Script: show_tree.sh
Copy and paste the following code into a file named show_tree.sh.
#!/usr/bin/env bash
# ---
# show_tree.sh
# A script to display a directory structure, using 'tree' if available,
# or a pure Bash fallback if not.
# ---
# --- Configuration ---
# Colors for the output
DIR_COLOR='\033[1;34m' # Bold Blue for directories
FILE_COLOR='\033[0;32m' # Green for files
NC='\033[0m' # No Color (to reset)
# --- Function to display usage information ---
show_usage() {
echo "Usage: $0 [DIRECTORY] [DEPTH]"
echo
echo "Shows the directory structure for the specified DIRECTORY."
echo
echo "Arguments:"
echo " DIRECTORY (Optional) The directory to scan. Defaults to the current directory ('.')."
echo " DEPTH (Optional) The maximum depth to display. Defaults to 3."
echo
echo "Examples:"
echo " $0 # Show current directory structure up to 3 levels deep"
echo " $0 /etc 2 # Show /etc structure up to 2 levels deep"
echo " $0 ~/Documents # Show Documents folder up to 3 levels deep"
exit 1
}
# --- Pure Bash recursive function to draw the tree ---
# This is used as a fallback if the 'tree' command is not installed.
# Arguments: $1:directory, $2:current_depth, $3:prefix
draw_tree_recursive() {
local current_dir="$1"
local current_depth="$2"
local prefix="$3"
# Use a glob that includes hidden files, but ignore '.' and '..'
# 'shopt' makes the glob work even if no files match
shopt -s nullglob dotglob
local entries=("$current_dir"/*)
shopt -u nullglob dotglob
local entry_count=${#entries[@]}
local i=0
# Stop if we've reached the desired depth
if [ "$current_depth" -ge "$max_depth" ]; then
return
fi
for entry in "${entries[@]}"; do
i=$((i + 1))
# Determine the connector a file/dir
if [ "$i" -eq "$entry_count" ]; then
connector="└── "
child_prefix="$prefix " # Last item, so no vertical line for children
else
connector="├── "
child_prefix="$prefix│ " # Not the last item, so add a vertical line
fi
# Check if the entry is a directory or a file and print with color
if [ -d "$entry" ]; then
echo -e "${prefix}${connector}${DIR_COLOR}$(basename "$entry")${NC}/"
# Recurse into the directory
draw_tree_recursive "$entry" $((current_depth + 1)) "$child_prefix"
else
echo -e "${prefix}${connector}${FILE_COLOR}$(basename "$entry")${NC}"
fi
done
}
# --- Main script logic ---
# Handle help argument
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
show_usage
fi
# Set target directory and depth from arguments
target_dir="${1:-.}" # Default to current directory if $1 is not set
max_depth="${2:-3}" # Default to 3 if $2 is not set
# Check if the target directory exists
if [ ! -d "$target_dir" ]; then
echo "Error: Directory '$target_dir' not found."
exit 1
fi
# Check if the depth is a number
if ! [[ "$max_depth" =~ ^[0-9]+$ ]]; then
echo "Error: Depth must be a non-negative integer."
exit 1
fi
echo -e "Directory structure for: ${DIR_COLOR}$(realpath "$target_dir")${NC}"
echo -e "Maximum depth: $max_depth"
echo "---"
# --- Primary Method: Use 'tree' if it exists ---
if command -v tree &> /dev/null; then
echo "Using 'tree' command..."
echo
# Use '--' to handle directory names that might start with a hyphen
tree -L "$max_depth" -- "$target_dir"
else
# --- Fallback Method: Use the pure Bash function ---
echo "NOTE: 'tree' command not found. Using pure Bash fallback."
echo " (For a better experience, install 'tree': sudo apt install tree / sudo yum install tree / brew install tree)"
echo
# Print the root directory itself
echo -e "${DIR_COLOR}$(basename "$target_dir")${NC}/"
# Start the recursion
draw_tree_recursive "$target_dir" 0 ""
fi
echo "---"
echo "Done."
How to Use
-
Save the Script: Save the code above into a file named show_tree.sh.
-
Make it Executable: Open your terminal and run this command to give the script permission to execute:
chmod +x show_tree.sh
-
Run it: You can now run the script from your terminal.
Examples
-
Show the current directory structure (up to 3 levels deep):
./show_tree.sh
-
Show the structure of /var/log (up to 2 levels deep):
./show_tree.sh /var/log 2
-
Show your home Documents folder:
./show_tree.sh ~/Documents
-
Get help:
./show_tree.sh --help
Script Explanation
- Shebang
#!/usr/bin/env bash: This ensures the script is run with the Bash shell, no matter where it's located.
- Configuration: Sets up ANSI color codes in variables for easy use and readability (
DIR_COLOR, FILE_COLOR, NC).
show_usage() Function: A standard function to print help information if the user requests it or provides invalid input.
- Argument Parsing:
target_dir="${1:-.}": This is a neat trick. It sets target_dir to the first argument ($1), but if $1 is empty, it defaults to . (the current directory).
max_depth="${2:-3}": Similarly, sets max_depth to the second argument or defaults to 3.
- Input Validation: The script checks if the provided directory actually exists and if the depth is a valid number. This prevents errors.
command -v tree &> /dev/null: This is the standard way to check if a command (tree) exists and is in the system's PATH. All output (&>) is sent to /dev/null so it doesn't clutter the screen.
tree Logic: If tree exists, the script simply runs tree -L "$max_depth" -- "$target_dir".
-L "$max_depth": Limits the level (depth) of the tree.
--: An important security and stability feature. It tells tree that any following arguments are not options, so it can correctly handle a directory named -mydir.
- Bash Fallback
draw_tree_recursive(): This is the core of the fallback.
- It takes the directory, current depth, and a line
prefix as arguments.
shopt -s nullglob dotglob: This is a robust way to get all files, including hidden ones (dotfiles), without getting . and ...
- It loops through each item in the directory.
- It cleverly determines whether to use
├── (for an intermediate item) or └── (for the last item).
- It updates the
prefix for the next level of recursion (│ or ) to draw the connecting lines correctly.