Course contentsShow
← Linux
Lesson 138 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Shell Options for Debugging

Leverage built-in shell features to trace execution paths in production.

In this lesson, you will learn how to use built-in shell options to make Bash scripts "talk" to you while they run, allowing you to trace execution paths in production environments.

When a script fails in production, it is often difficult to pinpoint exactly which line caused the error or what values your variables held at that specific moment. Instead of adding dozens of echo statements throughout your code, you can leverage Bash's built-in debugging flags.

The Trace Options

The most powerful tool for this is the set -x command (short for xtrace). When you enable this option, the shell prints every command it executes to standard error, preceded by a plus sign (+). This allows you to see the exact state of your code, including how variables have expanded, before the commands are run.

Consider this simple script:

#!/bin/bash
set -x  # Enable tracing

name="World"
echo "Hello, $name"

set +x  # Disable tracing

When you run this, the output will look like this:

+ name=World
+ echo 'Hello, World'
Hello, World

Debugging in Production

You don't always want to enable tracing for the entire script. If you are debugging a specific function or a block of code, you can toggle these options on and off:

  • set -x: Turns on the execution trace.
  • set +x: Turns off the execution trace.

If you are dealing with complex logic and need to see how your commands are being parsed, you can also use set -v (verbose). While -x shows you the commands after variable expansion, -v prints the lines of the script as they are read, effectively showing you the raw source code as it is being processed.

By strategically placing these toggles, you can observe the "flow" of your script in a live environment without manually injecting temporary debugging text into your logic.

Key Takeaway: Use set -x to gain instant visibility into how your script resolves variables and executes commands, turning the shell itself into a diagnostic tool.