Debug Mode in Bash

Debug mode in Bash is a useful feature that allows you to trace the execution of a script, helping you identify errors, understand the flow, and troubleshoot issues.

Debug mode in Bash is a useful feature that allows you to trace the execution of a script, helping you identify errors, understand the flow, and troubleshoot issues. When debug mode is enabled, Bash prints each command before executing it, along with the expanded values of variables and expressions.

Debug Using Trap

The magic line to add after shebang so that the script can be debugged in steps:

1#!/usr/bin/env bash
2trap 'echo "[DEBUG]# $BASH_COMMAND";read' DEBUG

Debug Process

Run the script, before each command is executed the output of what will be executed, then the interpreter begins to wait for the ENTER key to be pressed.

Если понимаем, что что-то пошло не так, нажимаем Ctrl+C и выходим из отладки.

Recipe

  • The trap command, which can intercept various signals, and in our case, it intercepts the DEBUG signal sent before executing a command.
  • The read command, which can wait for input from the keyboard (in this case, we only need either ENTER or Ctrl+C).
  • The environment variable $BASH_COMMAND, which is valid inside the trap command handler.

Option -x

The -x argument allows you to step through each line of the script in debugging mode:

1bash -x script.sh

Example

Here’s a good example (cat hello.sh):

1#!/usr/bin/env bash
2echo "Hello World\n"
3adding_string_to_number="s"
4v=$(expr 5 + $adding_string_to_number)

Here is the output of the running program (./hello.sh):

1Hello World
2
3expr: non-integer argument

This output is not enough. However, using the debug mode (bash -x hello.sh), you can get more details:

1+ echo Hello World\n
2Hello World
3+ adding_string_to_number=s
4+ expr 5 + s
5expr: non-integer argument
6+ v=

アリメクタ’s Blog

Watch. Read. Run. Repeat.

World’s Best Company Ask Me First

The first rule of Fight Club is: "You do not talk about Fight Club."

The second rule of Fight Club is: "You do not talk about Fight Club!"