Tux the PenguinA nice trick to keep in mind when you are busy creating a bash script in Linux is to allow for tracing, particularly when your script seems to be falling over in the strangest of places and you simply can’t pinpoint why!

Essentially tracing is the bash shell showing you line by line how your script is executing, most importantly with variable substitutions in place, meaning that you get to see exactly what your script is doing as it steps through line after line. An example as to how this would appear on your screen would be:

[craig]$ ./tracingexample.bash
+ number=1
+ ‘[‘ 1 = 1 ‘]’
+ echo ‘Number equals 1’
Number equals 1

In order to turn on tracing for your script, add a “- x” to the first line of your file, like this:

#!/bin/bash -x

Alternatively, you can also switch tracing on and off by using the “set -x” to turn tracing on and then “set +x” to turn it off again. For example:

set -x
if [ $number = “1” ]; then
echo “Number equals 1”
echo “Number does not equal 1”
set +x

Needless to say, the ability to trace through your scripts is quite a powerful tool to have at your disposal, particularly when you start working with more complex variable substitutions!