Skip to main content

πŸ“˜ Debugging & Troubleshooting in Bash β€” Advanced Setup


🎯 What You Will Learn

  1. Understand how debugging and troubleshooting work in Bash scripting and interactive sessions.
  2. Learn how to use built-in Bash debugging modes (x, v, set -e, trap) to find script errors.
  3. Explore PS4 prompt customization for visual debugging output.
  4. Apply debugging techniques to WordPress VPS scripts, such as WP-CLI backups, automation, and service restarts.
  5. 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​

PurposeDescription
Error IsolationPinpoint where a script fails or exits prematurely.
Performance AnalysisIdentify commands that slow down script execution.
SecurityDetect unintended command execution or unsafe variables.
Automation ReliabilityEnsure 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​

ScopeFilePurpose
Temporary (per session)Terminal or script headerOne-time debugging or tracing
User-Level~/.bashrcPersistent prompt and trace settings
System-Level/etc/profile.d/debug.shShared 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.

OptionDescriptionExample
set -xPrint commands as they executeset -x
set +xDisable trace outputset +x
set -eExit immediately on errorset -e
set -uTreat unset variables as errorsset -u
set -o pipefailDetect errors in piped commandsset -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 CaseCommandDescription
Debug plugin updatesbash -x wpupdate.shTrace plugin update automation
Check variable substitutionset -x in .bashrcView how $PATH and $WP_ENV are expanded
Test database export logicbash -v wpbackup.shValidate command flow for backups
Catch failing cron taskstrap 'echo "Error" >> log' ERRLog cron failures automatically
Monitor command execution timetime bash -x wpclean.shMeasure performance impact of cache cleaning

11. Common Debugging Commands​

CommandDescription
bash -x script.shStep-by-step execution trace
bash -v script.shShow commands before execution
set -eExit script on first error
set -x / set +xEnable/disable live tracing
trap '...' ERRCapture and handle errors
echo $?Display exit code of last command
tail -f /root/logs/bash-debug.logMonitor 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​

  1. Enable tracing only when needed β€” avoid leaking sensitive data (like passwords).
  2. Use PS4 customization to trace scripts line-by-line.
  3. Always log debug sessions instead of printing to screen in production.
  4. **Combine **set -euo pipefail for strong error detection.
  5. Validate exit codes with $? after critical commands.
  6. Test on staging servers first before enabling debug on production.
  7. Use traps to capture and log unexpected errors automatically.

14. Troubleshooting Checklist​

ProblemLikely CauseSolution
No output during debugset -x missingAdd set -x or run bash -x script.sh
Script exits silentlyMissing set -eAdd set -e to detect early failures
No line number in tracePS4 not definedUse PS4='+ (${BASH_SOURCE}:${LINENO}): '
Trap not triggeredNot catching ERRUse trap '...' ERR
Debug log emptyOutput not redirectedUse 2>&1 to include errors in output

15. Quick Lab​

Objective: Debug a WordPress database export automation.

  1. Create file:
nano /root/scripts/debug-wpbackup.sh

  1. 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."

  1. Run:
bash -x /root/scripts/debug-wpbackup.sh

  1. 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​

TermDefinition
set -xPrints each command before execution.
set -eStops script on first error.
PS4Defines debug trace format.
trapCaptures signals or errors to run custom actions.
pipefailEnsures errors inside pipelines are caught.
Exit CodeNumeric code returned by a command (0 = success).

17. Mini-Quiz​

  1. What does set -euxo pipefail do in Bash?
  2. How does PS4 improve debugging visibility?
  3. Why should you redirect debug output to a log file?
  4. What happens if you omit set -e in a script with multiple commands?
  5. How can trap be used to record unexpected script failures?

18. Summary​

  • Bash includes native debugging tools like x, v, set, and trap.
  • PS4 provides line-level trace information for deep inspection.
  • Combine set -euxo pipefail for 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.