LESSON · 1 OF 5

bash -x and set -x

bash -x and set -x

The single most useful bash debugging technique: turn on tracing and let the shell print every command as it runs, with variables expanded.

bash -x <script>

bash
bash -x /root/scripts/deploy.sh alice bob

Runs the script and prints every command before executing it, with variables expanded. You SEE what bash saw.

Output looks like:

+ user=alice
+ echo 'processing alice'
processing alice
+ user=bob
+ echo 'processing bob'
processing bob

Lines starting with + are the trace. Lines without are the script's actual output.

set -x inside the script

bash
some_setup

set -x                # trace from here
problematic_part
set +x                # trace off

more_stuff

Turn tracing on for a specific section instead of the whole script. Useful when the script is long and you only care about one function.

Combining with -e

bash
bash -xe /root/scripts/deploy.sh

Trace AND exit on first error. Perfect for finding the exact command that failed.

Reading the output

  • + command args - a command about to run.
  • +++ command args - nested subshells add more +s.
  • Regular output - the script's actual stdout.

If you see + some_var= (empty), the variable you thought had a value is actually empty. Very common source of "why doesn't this work?" moments.

Spin up a fresh environment and practice live.
linux-devops-basic · fresh machine · ready in under a minute