Debugging Bash Script

When programming in any language there will be times when a script doesn't work as intended. This is where debugging comes in. Bash script provides a few features to aid in finding issues in the code. In order to debug a whole script, it can be run in debug mode as follows.

bash -x ./demo.sh

The following script sets two variables and then includes them in a string that is output to the terminal.

PNAME=Fred
BIRTHDAY="6 March"

echo "${PNAME}'s birthday is on ${BIRTHDAY}."

The resulting output, when not run in debug mode can be seen below.

Fred's birthday is on 6 March.

As can be seen with what follows, running in debug mode produces more output to the terminal.

+ PNAME=Fred
+ BIRTHDAY='6 March'
+ echo 'Fred'\''s birthday is on 6 March.'
Fred's birthday is on 6 March.

The lines that start with a plus symbol relate to the lines of code in the script. Any lines that don't have a plus symbol at the start is output from the previous line of code.

Often it isn't necessary to debug an entire script. In this situation, within the script, place 'set -x' before the first line that needs debugging and 'set +x' after the last.

PNAME=Fred

set -x

BIRTHDAY="6 March"

echo "${PNAME}'s birthday is on ${BIRTHDAY}."

set +x

This script can be run in the normal way.

./demo.sh

The output to the terminal now is as follows.

++ BIRTHDAY='6 March'
++ echo 'Fred'\''s birthday is on 6 March.'
Fred's birthday is on 6 March.
++ set +x