← Back to Bash Course | Chapter 12: Error Handling & Debugging | Lesson 9 of 12

Debug Mode (set -x)

set -x is like slow-motion replay: the shell shows each step it is about to do, with the real values filled in, so you can see where a script goes wrong.

In this page:

  1. Debug Mode (set -x)
Syntax
bash
set -x
commands
set +x

Debug Mode (set -x)

set -x makes Bash print each command with its expanded arguments before running it, which is invaluable for tracing exactly what a script does.

set +x turns it back off. Debug tracing is usually enabled temporarily around a suspicious section rather than for an entire large script.

Note: Wrap only the suspicious section in set -x / set +x rather than tracing the whole script, to keep the output readable.

Example: Debug Mode (set -x)

bash
#!/bin/bash
echo "Before debug mode"

set -x
x=5
y=$((x * 2))
set +x

echo "After debug mode, y=$y"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Leaving set -x on in production, which prints secrets.
  2. Forgetting to turn it off with set +x.
  3. Not knowing that debug output goes to standard error.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.