Skip to content

How to Debug in Bash Script



Bash is a command-line shell that allows users to interact with their operating system. When writing Bash scripts, errors can occur which can be difficult to identify and fix. However, Bash provides several tools to help debug these errors. In this post, we will discuss how to debug in Bash.

Setting Debugging Options

One way to debug Bash scripts is to set debugging options. This can be done by adding the -x option to the first line of your script or by running the script with the -x option from the command line. This option will display each command as it is executed, along with any variables that are expanded.

For example, if the first line of your script is #!/bin/bash, you can modify it to #!/bin/bash -x. Alternatively, you can run the script with the command bash -x

Run bash scripts in a safer way

bash -x      debug execution
bash -n      syntax test
set -e # exit immediately on error
set -u # treat all undefined variables as errors
set -x # debug switch
set -o pipefail # in a pipeline of commands, if any command fails (returns non-zero), the entire pipeline operation is considered a failure

set -euxo pipefail
Buy Me a Coffee