How to Debug in Bash

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 -eexit immediately when a command failsset -uview undefined variable as errorset -xrun in debug modeset -o pipefailThis 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.
#!/bin/bash
trap 'echo "The value of x is $x"' SIGINT
x=10
while true; do
echo "Waiting for SIGINT"
sleep 1
done
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.
#!/bin/bash
exec 2> debug.log
set -x
echo "Starting script"
x=10
echo "The value of x is $x"
echo "Ending script"
Some of the content is generated by AI, please be cautious in identifying it.