0Pricing
DevOps Bootcamp · Lesson

Debugging Bash Scripts (set -x, trap)

Discover methods to debug your Bash scripts, including tracing execution and using 'trap' for error handling.

Debugging Bash Scripts (set -x, trap) is a free DevOps Bootcamp lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the DevOps Bootcamp learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Debug Your Scripts?

Even the best scripts can have bugs! Debugging is the process of finding and fixing these errors.

It's a crucial skill for any developer, helping you understand what your script is doing step-by-step and where things might be going wrong.

In this lesson, you'll learn powerful Bash tools to trace execution and handle unexpected events.

Trace Your Script with `set -x`

One of the simplest and most effective debugging tools in Bash is set -x. It enables command tracing.

  • When active, Bash prints each command and its arguments to standard error (which usually means your terminal) just before executing it.
  • This output includes the state of variables after expansion, giving you a clear view of what Bash is about to do.
  • It's like watching your script execute in slow motion!

Seeing `set -x` Work

Let's see set -x in action. Notice how the shell prints each command after variable expansion, prefixed with a + sign.

Try running this example:

#!/bin/bash

# Enable command tracing
set -x

NAME="Coddy"
MESSAGE="Hello, $NAME!"

echo $MESSAGE

# This command will intentionally fail
ls -l /nonexistent_directory

# Disable command tracing
set +x

echo "Tracing is now off."

Understanding Trace Output

When set -x is enabled, you'll see lines starting with a + symbol. This indicates a trace output.

  • The + is followed by the command Bash is about to execute, along with its arguments after any variable or command substitutions.
  • This is incredibly useful for seeing the exact values of variables and the precise command being run.
  • It helps pinpoint issues like incorrect paths, empty variables, or unintended command structures.

Controlling `set -x` Scope

You don't always need to trace your entire script. You can enable set -x for specific sections:

  • Use set -x to turn tracing on.
  • Use set +x to turn tracing off.

This allows you to focus your debugging efforts on problematic parts of your script without being overwhelmed by output from stable sections.

Handle Events with `trap`

The trap command allows you to catch signals and other events, then execute a command when they occur. This is powerful for:

  • Cleanup: Ensuring temporary files are removed.
  • Error handling: Responding to failed commands.
  • Graceful exits: Handling user interruptions like Ctrl+C.

The basic syntax is trap 'command_to_execute' SIGNAL_OR_EVENT.

Cleanup with `trap EXIT`

The EXIT pseudo-signal is special. A command trapped with EXIT will run just before your script terminates, regardless of how it exits (success, failure, or interruption).

This is perfect for cleanup tasks, like deleting temporary files. Try running this script:

#!/bin/bash

TEMP_FILE="/tmp/coddy_temp_$(date +%s).txt"

# Trap the EXIT signal to remove the temp file
trap 'echo "Cleaning up: Removing $TEMP_FILE"; rm -f "$TEMP_FILE"' EXIT

echo "Script started. Creating temporary file..."
touch "$TEMP_FILE"
echo "Temporary file created: $TEMP_FILE"

# Simulate some work
sleep 2

echo "Script logic completed. Exiting..."

Catch Errors with `trap ERR`

The ERR pseudo-signal triggers when a command exits with a non-zero status (i.e., it fails). This allows you to perform actions specifically when an error occurs.

Note: trap ERR only works if the command is not part of an if, while, or until condition, or if its return value is not explicitly checked (e.g., command || true).

#!/bin/bash

# Trap ERR to report the error line number
trap 'echo "Error detected on line $LINENO! Exiting."' ERR

echo "Starting script with an intentional error..."

# This command will fail and trigger the ERR trap
ls /this/path/does/not/exist

echo "This line will NOT be reached if an error occurs."

Responding to Signals (INT, TERM)

trap can also catch standard Linux signals. Common ones include:

  • INT (Interrupt): Sent when you press Ctrl+C.
  • TERM (Terminate): A request to terminate a process gracefully.

Trapping these signals lets your script perform cleanup or save state before shutting down, rather than abruptly quitting.

#!/bin/bash

# Trap INT (Ctrl+C) to exit gracefully
trap 'echo "\nCaught Ctrl+C! Exiting gracefully..."; exit 1' INT

echo "Running a continuous task. Press Ctrl+C to stop."

while true; do
  echo "Working... $(date)"
  sleep 3
done

Debugging Check

Let's check your understanding of Bash debugging techniques.

Recap: Debugging Your Scripts

Great job! You've learned essential tools to debug your Bash scripts:

  • set -x: Enables command tracing, showing you exactly what Bash executes. Use set +x to turn it off.
  • trap: Allows you to execute commands in response to specific events or signals.
  • `trap EXIT`: Ensures cleanup tasks run before the script ends.
  • `trap ERR`: Catches commands that exit with a non-zero status.
  • `trap INT`/`TERM`: Handles user interruptions or termination requests gracefully.

Mastering these techniques will significantly improve your ability to troubleshoot and create robust Bash scripts!

Frequently asked questions

Is the “Debugging Bash Scripts (set -x, trap)” lesson free?

Yes — the full text of “Debugging Bash Scripts (set -x, trap)” is free to read here on the web, and the DevOps Bootcamp course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the DevOps Bootcamp course, upgrade to CoddyKit PRO.

What will I learn in “Debugging Bash Scripts (set -x, trap)”?

Discover methods to debug your Bash scripts, including tracing execution and using 'trap' for error handling. You practise DevOps Bootcamp with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start DevOps Bootcamp?

No prior experience is required. DevOps Bootcamp on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Debugging Bash Scripts (set -x, trap)” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this DevOps Bootcamp lesson?

Yes. Every DevOps Bootcamp lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Debugging Bash Scripts (set -x, trap)
  2. Error Handling & Exit Status
  3. Scripting Best Practices & Linting
  4. Testing Bash Scripts with Bats
← Back to DevOps Bootcamp