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:
Syntax
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)
#!/bin/bash
echo "Before debug mode"
set -x
x=5
y=$((x * 2))
set +x
echo "After debug mode, y=$y"
Login to try C/C++/Java/PHP code in the editor
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
- Leaving
set -xon in production, which prints secrets. - Forgetting to turn it off with
set +x. - Not knowing that debug output goes to standard error.
🔒
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first:
- Exit Codes and Checking $? Correctly
- set -e and set -u
- Error Handling
- set -e (Exit on Error) and Its Gotchas
- Logging
- set -u (Undefined Variables) and set -x (Trace Mode)
- Script Arguments with getopts
- trap ERR for Custom Error Handling
- Debug Mode (set -x)
- Writing a Custom Error/die Function
- Portability
- Validating Script Input and Arguments