How to Debug a Bash script?

Posted on In QA

How to debug a Bash script if it has some bugs? Common techniques like printing varibles out for checking apply for bash too. For bash, I also use 2 bash-specific techniques.

Use errexit option

Run the script with -e option like bash -e your-script.sh or add set -o errexit to the beginning of the script.

errexit makes bash exit immediately if one statement’s return code is not 0. This way, you know which statement goes wrong.

Use xtrace option

Run the script with -x option like bash -x your-script.sh or add set -o xtrace to the beginning of the script.

The -x option will make bash print statements executed so that you know what is going on.

One example

For example,

#!/bin/bash

set -x

i=0
let i=i+1

echo $i
false # this will stop the script run with -e
date

The execution of that script with bash -e script.sh will print

+ i=0
+ let i=i+1
+ echo 1
1
+ false

By combining the 2 techniques together, which statement/step went wrong is printed out on the STDOUT.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *