π Debugging & Troubleshooting in Bash β Advanced Setup
π― What You Will Learn
- Understand how debugging and troubleshooting work in Bash scripting and interactive sessions.
- Learn how to use built-in Bash debugging modes (
x,v,set -e,trap) to find script errors. - Explore PS4 prompt customization for visual debugging output.
- Apply debugging techniques to WordPress VPS scripts, such as WP-CLI backups, automation, and service restarts.
- Master error handling best practices, including exit codes, logging, and safe execution.
1. What Is Bash Debuggingβ
Bash debugging refers to techniques and options that help you:
- Understand what commands Bash executes in a script.
- See variable values during execution.
- Identify syntax errors, logic mistakes, and unexpected behavior. Example:
bash -x myscript.sh
Shows every command Bash runs β helpful when a script silently fails.β
2. Why Debugging Mattersβ
| Purpose | Description |
| Error Isolation | Pinpoint where a script fails or exits prematurely. |
| Performance Analysis | Identify commands that slow down script execution. |
| Security | Detect unintended command execution or unsafe variables. |
| Automation Reliability | Ensure VPS maintenance and WP-CLI tasks run predictably. |
Debugging is essential when you automate backups, database dumps, or plugin updates β since one error can affect multiple sites.β
3. Where Debugging Configuration Livesβ
| Scope | File | Purpose |
| Temporary (per session) | Terminal or script header | One-time debugging or tracing |
| User-Level | ~/.bashrc | Persistent prompt and trace settings |
| System-Level | /etc/profile.d/debug.sh | Shared system-wide tracing configurations |
4. File Locations (Tree View)β
User Configuration
/home/
βββ donnyariw/
βββ .bashrc
βββ .bashrc.d/
β βββ debug.sh
β βββ wp-cli.sh
β βββ redis.sh
β βββ mysql.sh
βββ .bash_profile
βββ logs/
βββ bash-debug.log
System Configuration
/etc/
βββ profile.d/
βββ debug.sh
βββ wp-monitor.sh
βββ system-health.sh
5. Debugging Modes and Optionsβ
a. Verbose Mode (v)β
Displays each command as itβs read, before execution.
bash -v script.sh
Use Case: Check for syntax errors or typos in long scripts.β
b. Execution Trace Mode (x)β
Prints each command as it executes, including variable expansion.
bash -x script.sh
Output:
+ site=dev-wpstrategist
+ wp db export /root/wpbackup/dev-wpstrategist.sql --allow-root
Use Case: Ideal for tracing logic flow and verifying variable values in scripts.β
c. Enable Within a Scriptβ
Instead of enabling from the command line, you can activate debug mode inside the script.
#!/bin/bash
set -x # Start debug mode
echo "Starting backup..."
wp db export /root/wpbackup/db.sql --allow-root
set +x # Stop debug mode
echo "Backup completed."
Output:
+ echo 'Starting backup...'
Starting backup...
+ wp db export /root/wpbackup/db.sql --allow-root
Success: Exported database.
+ echo 'Backup completed.'
Backup completed.
d. Combine Optionsβ
You can mix both:
bash -vx script.sh
Shows both command reading and execution.β
6. Using the set Command for Debuggingβ
set provides fine-grained control over shell behavior.
| Option | Description | Example |
set -x | Print commands as they execute | set -x |
set +x | Disable trace output | set +x |
set -e | Exit immediately on error | set -e |
set -u | Treat unset variables as errors | set -u |
set -o pipefail | Detect errors in piped commands | set -o pipefail |
Example:β
set -euxo pipefail
wp db export /root/wpbackup/db.sql --allow-root
Ensures script stops immediately if any command fails or variable is undefined.β
7. Customizing the PS4 Promptβ
PS4 defines how each traced command (set -x) appears.
Default:
PS4='+ '
Customize to include line numbers and script names:
export PS4='+ (${BASH_SOURCE}:${LINENO}): '
Example output:
+ (wpbackup.sh:12): site=dev-wpstrategist
+ (wpbackup.sh:13): wp db export /root/wpbackup/dev-wpstrategist.sql --allow-root
β This helps trace complex WordPress automation scripts line by line.β
8. Using trap for Error Handlingβ
trap executes a command when a specific signal or error occurs.
a. Basic Exampleβ
trap 'echo "An error occurred at line $LINENO"; exit 1' ERR
b. WordPress Backup Exampleβ
#!/bin/bash
trap 'echo "Error: Backup failed at line $LINENO" >> /root/logs/bash-debug.log' ERR
wp db export /root/wpbackup/db.sql --allow-root
If the backup fails, the error is logged instead of silently failing.β
9. Redirecting Debug Output to Log Fileβ
Redirect trace output for later review:
bash -x script.sh > /root/logs/bash-debug.log 2>&1
Example:
cat /root/logs/bash-debug.log
Output:
+ wp db export /root/wpbackup/db.sql --allow-root
Success: Exported database.
10. WordPress VPS Use Casesβ
| Use Case | Command | Description |
| Debug plugin updates | bash -x wpupdate.sh | Trace plugin update automation |
| Check variable substitution | set -x in .bashrc | View how $PATH and $WP_ENV are expanded |
| Test database export logic | bash -v wpbackup.sh | Validate command flow for backups |
| Catch failing cron tasks | trap 'echo "Error" >> log' ERR | Log cron failures automatically |
| Monitor command execution time | time bash -x wpclean.sh | Measure performance impact of cache cleaning |
11. Common Debugging Commandsβ
| Command | Description |
bash -x script.sh | Step-by-step execution trace |
bash -v script.sh | Show commands before execution |
set -e | Exit script on first error |
set -x / set +x | Enable/disable live tracing |
trap '...' ERR | Capture and handle errors |
echo $? | Display exit code of last command |
tail -f /root/logs/bash-debug.log | Monitor log file live |
12. Example β Debugging a WP Backup Scriptβ
**File: **/root/scripts/wpbackup.sh
#!/bin/bash
set -euxo pipefail
trap 'echo "Error occurred at line $LINENO" >> /root/logs/bash-debug.log' ERR
PS4='+ (${BASH_SOURCE}:${LINENO}): '
site="dev-wpstrategist"
backup_dir="/root/wpbackup"
echo "Starting backup for $site..."
wp db export ${backup_dir}/${site}-$(date +%F).sql --path=/home/$site/public_html --allow-root
echo "Backup completed successfully."
Run:
bash -x /root/scripts/wpbackup.sh
Output:
+ (wpbackup.sh:6): site=dev-wpstrategist
+ (wpbackup.sh:8): echo 'Starting backup for dev-wpstrategist...'
Starting backup for dev-wpstrategist...
+ (wpbackup.sh:9): wp db export /root/wpbackup/dev-wpstrategist-2025-10-13.sql --path=/home/dev-wpstrategist/public_html --allow-root
Success: Exported database.
If something fails:
Error occurred at line 9
is appended to /root/logs/bash-debug.log.β
13. Best Practicesβ
- Enable tracing only when needed β avoid leaking sensitive data (like passwords).
- Use PS4 customization to trace scripts line-by-line.
- Always log debug sessions instead of printing to screen in production.
- **Combine **
set -euo pipefailfor strong error detection. - Validate exit codes with
$?after critical commands. - Test on staging servers first before enabling debug on production.
- Use traps to capture and log unexpected errors automatically.
14. Troubleshooting Checklistβ
| Problem | Likely Cause | Solution |
| No output during debug | set -x missing | Add set -x or run bash -x script.sh |
| Script exits silently | Missing set -e | Add set -e to detect early failures |
| No line number in trace | PS4 not defined | Use PS4='+ (${BASH_SOURCE}:${LINENO}): ' |
| Trap not triggered | Not catching ERR | Use trap '...' ERR |
| Debug log empty | Output not redirected | Use 2>&1 to include errors in output |
15. Quick Labβ
Objective: Debug a WordPress database export automation.
- Create file:
nano /root/scripts/debug-wpbackup.sh
- Add content:
#!/bin/bash
set -euxo pipefail
trap 'echo "Error at line $LINENO" >> /root/logs/bash-debug.log' ERR
PS4='+ (${BASH_SOURCE}:${LINENO}): '
site="dev-wpstrategist"
echo "Starting debug for $site..."
wp db export /root/wpbackup/${site}-$(date +%F).sql --path=/home/$site/public_html --allow-root
echo "Backup completed successfully."
- Run:
bash -x /root/scripts/debug-wpbackup.sh
- Check log:
cat /root/logs/bash-debug.log
β Youβll see a full trace of your WP backup process with line numbers, variables, and exit status.β
16. Glossaryβ
| Term | Definition |
set -x | Prints each command before execution. |
set -e | Stops script on first error. |
PS4 | Defines debug trace format. |
trap | Captures signals or errors to run custom actions. |
pipefail | Ensures errors inside pipelines are caught. |
| Exit Code | Numeric code returned by a command (0 = success). |
17. Mini-Quizβ
- What does
set -euxo pipefaildo in Bash? - How does
PS4improve debugging visibility? - Why should you redirect debug output to a log file?
- What happens if you omit
set -ein a script with multiple commands? - How can
trapbe used to record unexpected script failures?
18. Summaryβ
- Bash includes native debugging tools like
x,v,set, andtrap. - PS4 provides line-level trace information for deep inspection.
- Combine
set -euxo pipefailfor strong safety and failure detection. - Always log debug output for reproducibility and auditing.
- Ideal for troubleshooting WordPress automation scripts, WP-CLI backups, and VPS maintenance tasks.
- Debugging is not only about finding errors β itβs about building resilient, transparent automation.