</>
Skip to content
Bash lessons (29/29)

Bash — Debugging

Set options

#!/bin/bash
set -x  # Print commands before execution
set -e  # Exit on error
set -u  # Error on undefined variables
set -o pipefail  # Catch pipe errors

Trace execution

#!/bin/bash
set -x
# Commands will be printed before execution
echo "This will be traced"

Trap for debugging

#!/bin/bash
trap 'echo "Error on line $LINENO"' ERR
trap 'echo "Script interrupted"' INT

Debug functions

debug() {
    [[ "${DEBUG:-false}" == "true" ]] && echo "[DEBUG] $*"
}

DEBUG=true debug "Variable: $var"

Common errors

# Unquoted variables
# Bad:  rm $file
# Good: rm "$file"

# Missing shebang
# Always start with #!/bin/bash

# Unused variables
# Use set -u to catch

Mini Practice

Write Bash code that:

  1. Uses set -x for tracing
  2. Sets up trap for debugging
  3. Creates a debug function
  4. Demonstrates common error patterns

Up Next

In the next lesson, you'll learn about Security — writing secure scripts.

Related Topics

Frequently Asked Questions about Debugging

What is Debugging in Bash?

Debugging is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Debugging?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Debugging.

Why is Debugging important in Bash?

Debugging is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.