0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use set -x in Bash for Debugging Scripts

Use set -x in bash to turn on debugging, which prints each command and its arguments as they execute. To stop debugging, use set +x. This helps you see what your script is doing step-by-step.
📐

Syntax

The basic syntax to enable debugging in bash scripts is:

  • set -x: Turns on debugging mode, printing commands and their arguments before execution.
  • set +x: Turns off debugging mode.

You can place set -x anywhere in your script to start tracing from that point, and set +x to stop it.

bash
set -x
# commands to debug
set +x
💻

Example

This example shows how set -x prints each command as it runs, helping you follow the script's flow.

bash
#!/bin/bash

set -x
name="Alice"
echo "Hello, $name!"
set +x
echo "Debugging stopped."
Output
+ name=Alice + echo "Hello, Alice!" Hello, Alice! + set +x Debugging stopped.
⚠️

Common Pitfalls

Common mistakes when using set -x include:

  • Forgetting to turn off debugging with set +x, which can clutter output.
  • Using set -x globally in large scripts, making output hard to read.
  • Not realizing sensitive data (like passwords) will be printed in debug output.

Use set -x only around the code you want to debug.

bash
# Wrong way: debugging entire script
set -x
password="secret"
echo "Password is $password"
# Output will show the password in plain text

# Right way: limit debugging
password="secret"
set -x
echo "Password is $password"
set +x
📊

Quick Reference

CommandDescription
set -xEnable debugging: print commands and arguments as they run
set +xDisable debugging
# ...Place these commands around code sections to control debugging
echoPrint output, useful to see variable values during debugging

Key Takeaways

Use set -x to enable command tracing and see script execution details.
Turn off tracing with set +x to avoid cluttering output.
Place set -x and set +x around specific code blocks for focused debugging.
Be cautious as debugging prints all commands, including sensitive data.
set -x helps find errors by showing exactly what commands run and their arguments.