TExcelTAD
Home › Automation Scripting: Bash, Python & Go › Debugging: bash -n, set -x and Dry Runs

Debugging: bash -n, set -x and Dry Runs

When a script misbehaves in CI at 3 a.m., you usually cannot attach a debugger. What you can do is check its syntax before it runs, make it print what it actually executes, and run it in a mode that shows what it would do without doing it. This lesson covers those three tools.

bash -n: syntax check without running

bash -n script parses the file and reports syntax errors without executing a single command. It is cheap enough to run on every script in a pre-commit hook or CI job:

bash · try it yourself
cat > broken.sh <<'SCRIPT'
for host in web-1 web-2; do
  if [ "$host" = web-1 ]; then
    echo "primary: $host"
  fi
echo "done"
SCRIPT
bash -n broken.sh; echo "-> status $?"
printf 'echo "ok"\n' > fine.sh
bash -n fine.sh; echo "-> status $?"
broken.sh: line 6: syntax error: unexpected end of file
-> status 2
-> status 0

-n only finds what the parser finds: an unclosed loop, a missing fi, a stray quote. A misspelt command or variable is still valid syntax; that is what ShellCheck is for.

set -x: trace every command

set -x (xtrace) prints each command after expansion, prefixed by PS4 (default + ). Expansion is the useful part: you see the values that were really used, which is where quoting bugs show themselves. A better PS4 adds the file, line and function:

bash · try it yourself
cat > deploy.sh <<'SCRIPT'
set -euo pipefail
PS4='+ ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
release_dir() { echo "releases/$1"; }
version="1.4 rc1"
set -x
target=$(release_dir $version)
mkdir -p "$target"
set +x
ls releases
SCRIPT
bash deploy.sh
++ deploy.sh:6:main: release_dir 1.4 rc1
++ deploy.sh:3:release_dir: echo releases/1.4
+ deploy.sh:6:main: target=releases/1.4
+ deploy.sh:7:main: mkdir -p releases/1.4
+ deploy.sh:8:main: set +x
1.4

The trace shows the bug at once: release_dir received two arguments (1.4 and rc1) because $version was not quoted, so the directory is releases/1.4. The first character of PS4 is repeated once per level of nesting, so the ++ lines ran inside the $( ) command substitution. set +x turns tracing off again, so you can trace just the suspicious part. To trace a whole script without editing it, run bash -x script.sh.

Two production tips:

  • Secrets end up in traces. curl -H "Authorization: Bearer $TOKEN" is printed with the token expanded. Turn tracing off around such lines ({ set +x; } 2>/dev/null), and never leave set -x on by default in CI logs that others can read.
  • Send the trace elsewhere. exec 9>trace.log; BASH_XTRACEFD=9 writes the trace to a file and keeps stderr for real messages.

Dry runs: show, don't do

A --dry-run flag lets people (and code reviewers) see what a destructive script would do. The cleanest way is a single run wrapper through which every state-changing command goes. printf '%q' prints each argument quoted exactly as the shell would need it, so the output can be copied and run:

bash · try it yourself
cat > cleanup-releases.sh <<'SCRIPT'
set -euo pipefail
DRY_RUN=${DRY_RUN:-1}             # safe by default: set DRY_RUN=0 to really delete
run() {
  if [ "$DRY_RUN" = 1 ]; then
    printf 'DRY RUN:'; printf ' %q' "$@"; printf '\n'
  else
    "$@"
  fi
}
for dir in releases/*; do
  case ${dir##*/} in
    1.4*) echo "keeping $dir" ;;
    *)    run rm -rf -- "$dir" ;;
  esac
done
SCRIPT
mkdir -p "releases/1.2" "releases/1.3 hotfix" "releases/1.4"
bash cleanup-releases.sh
echo "--- still there: $(ls releases | wc -l)"
DRY_RUN=0 bash cleanup-releases.sh
ls releases
DRY RUN: rm -rf -- releases/1.2
DRY RUN: rm -rf -- releases/1.3\ hotfix
keeping releases/1.4
--- still there: 3
keeping releases/1.4
1.4

printf %q escaped the space in 1.3 hotfix, so you can see exactly which argument would be passed. Making dry run the default for destructive scripts, with an explicit opt-in to really act, is a habit that has saved many production systems; Terraform's plan/apply split is the same idea at a larger scale.

Tip: A dry run only tells the truth if the read-only parts still run for real. Query, list and compute as usual; route only the changes through run.

Test yourself

What does bash -n script.sh do?

  1. Runs the script without network
  2. Parses the script and reports syntax errors without running it
  3. Runs it with tracing
  4. Formats the script

In the set -x example, how did the trace reveal the bug?

  1. It printed an error message
  2. It showed release_dir 1.4 rc1: the unquoted variable was split into two arguments
  3. It showed the function was undefined
  4. It did not; the bug was found by ShellCheck

Why does the run wrapper print arguments with printf '%q'?

  1. To colour them
  2. So each argument is shown quoted exactly as the shell would need it, making spaces and special characters visible
  3. Because echo cannot print dashes
  4. To hide secrets