Skip to content

Exit Codes & Debugging

Every BASH script must handle errors gracefully. Exit codes—numeric values returned by commands (0 for success, non-zero for failure)—are the foundation of robust error handling. By explicitly checking exit codes and leveraging built-in debugging tools, you can create scripts that self-diagnose and fail safely.


Checking Exit Codes with $?

Every command in BASH returns an exit code. Use $? to capture and inspect it.

Basic Checks

ls /nonexistent_dir && echo "Success" || echo "Failure"
# Output: Failure

Conditional Logic

if ! grep -q "pattern" file.txt; then
    echo "Pattern not found"
fi

Chaining Commands

Use && (success) and || (failure) to chain commands:

mkdir -p /tmp/data && echo "Directory created" || echo "Creation failed"


Using set -e for Script Termination

The set -e option causes the script to exit immediately if any command returns a non-zero exit code.

Example Script

#!/bin/bash
set -e
invalid_command  # This fails, script exits here
echo "This line is unreachable"

Caveats

  • set -e ignores errors in subshells (e.g., (...)) or commands with ||.
  • Combine with set -u (fail on undefined variables) for stricter validation:
    set -eu
    echo "$UNDEFINED_VAR"  # Fails immediately
    

Enabling Debugging with set -x

The set -x flag prints each command as it's executed, useful for tracing script flow.

Debug Output

#!/bin/bash
set -x
echo "Debugging enabled"
ls /nonexistent_dir  # Fails, but debug output is shown

Redirecting Debug Output

Use BASH_XTRACEFD to redirect debug messages to a file:

#!/bin/bash
set -x
BASH_XTRACEFD=3
exec 3> debug.log
echo "This will be logged"


Key takeaways

  • Always check exit codes with $? to handle errors explicitly.
  • Use set -e to terminate scripts on failures, but be aware of its limitations.
  • Enable debugging with set -x to trace script execution and identify issues.
  • Combine set -e and set -x for rapid troubleshooting during development.
  • Prioritize clarity: let exit codes and debugging output guide your error resolution.