Skip to content

Debug in bash



Bash is a scripting language used in Linux systems. Debugging is a crucial task for any programmer, and it is not an exception in Bash programming. Debugging in bash can be challenging, especially for beginners. In this blog post, we will discuss how to debug in bash and make your programming experience more comfortable and efficient.

To run Bash scripts in a safer way, here are some tips and usage patterns to debug bash scripts.

Setting Debugging Options

The first step in debugging bash scripts is to enable debugging options. Bash provides various options to enable debugging. We can set these options by using the set command with the -x or -v options. The -x option enables debugging by printing each command before executing it. The -v option enables debugging by printing each command before executing it, but it also includes the variables’ values. We can also enable debugging for a specific block of code by enclosing it within set -x and set +x statements.

command line options

bash -x ## debug
bash -n ## test syntax

set options

  • set -e exit immediately when a command fails
  • set -u view undefined variable as error
  • set -x run in debug mode
  • set -o pipefail This tells the script that if any of the steps (not in a block construction) fail (exit with non-zero), the whole script should halt in place and the script will exit with the failure message of the failed step.

Put them together

set -euxo pipefail

Using Traps

Traps are commands that execute when a signal is received by the script. We can use traps to debug bash scripts by setting a trap for a specific signal and then printing the values of variables or other relevant information. For instance, we can use the following code to print the value of a variable when a script receives a SIGINT signal.

trap 'echo "The value of x is $x"' SIGINT
while true; do
  echo "Waiting for SIGINT"
  sleep 1

Adding Debug Information to Log Files

Another useful technique for debugging in bash is to add debug information to log files. We can use the echo command to print debug information and redirect it to a log file. We can then analyze the log file to identify the errors in the script. For instance, we can use the following code to print debug information to a log file.

exec 2> debug.log
set -x
echo "Starting script"
echo "The value of x is $x"
echo "Ending script"


Debugging is an essential task in bash programming. By following the techniques discussed in this blog post, you can easily debug your bash scripts and make your programming experience more efficient. Remember to set debugging options, use traps, and add debug information to log files to make your debugging process more comfortable and efficient.

Leave a message