Debugging Bash scripts systematically

Summary

On Hackaday, Al Williams shows how to debug Bash scripts systematically instead of scattering echo everywhere. Tracing with -x prints every executed line, and the bashdb debugger offers breakpoints, single-stepping and watches like gdb. bashdb is itself written in Bash and uses a trap provided specifically for debuggers.

Tracing with -x

The -x option can be set in three ways: with set -x in the running shell (and set +x to turn it off), when calling with bash -x ./script.sh, or permanently in the first line as #!/bin/bash -x. Lines prefixed with a plus sign show what is being executed; all others are output of the script.

In the running shell, everything the prompt itself executes gets in the way. Calling with bash -x therefore keeps the trace cleaner.

The bashdb debugger

bashdb is started with bashdb script.sh; its version must match the installed Bash. The commands resemble gdb: list shows the source with line numbers, break and tbreak set breakpoints, condition makes them conditional, backtrace shows the call stack, step, next and skip move on in single steps, display and watch observe variables.

According to Williams, Ubuntu and similar distributions no longer carried bashdb in their repositories as early as 2019; you download it from SourceForge.

Ideas

  • bash -x shows every executed line with a plus sign.
  • The -x option can also be written into the shebang line.
  • bashdb brings breakpoints and single-stepping to shell scripts.
  • Conditional breakpoints save many runs.
  • Bash's debug trap fires after every statement.
  • Static checking tools prevent errors before you have to debug.

Insights

  • printf debugging works but scales poorly with complexity.
  • The shell comes with more diagnostic tools than most people use.

Quotes

  • The best way to not have to debug shell scripts is to not put bugs in to start with. (Al Williams)

Facts

  • Debian last shipped bashdb in version 7 (Wheezy).
  • set +x turns tracing off again.
  • tbreak sets a breakpoint that triggers only once.
  • bashdb is itself a Bash program.

References

Remarks

  • For avoiding errors, Williams refers to an older Hackaday post about lint tools for shell scripts; it is about ShellCheck.

Recommendations

  • Set PS4='+${BASH_SOURCE}:${LINENO}: ' so the -x trace names file and line.
  • Run ShellCheck over every script before you debug it.
  • Switch -x on selectively with set -x and set +x only around the suspicious section.

Read the original article

Search the Web Archive

Found a mistake or have something to add? Get in touch.