Using set to debug scripts

You can use the set commands to help with debugging your scripts. There are two common options to set, x and v. Here is a description of each.

Note that a - activates the set while a + deactivates it. If that sounds backwards to you it is because it is backwards.

Use:

  • set -x: to display the expanded trace before running the command
  • set -v: to display the input line as it is parsed

Take a look at Script 5 which shows what set -x does:

Chapter 9 - Script 5 and Script 6

#!/bin/sh
#
# 6/7/2017
#
set -x                       # turn debugging on

echo "Chapter 9 - Script 5"

x=0
while [ $x -lt 5 ]
do
 echo "x: $x"
 let x++
done

echo "End of script5"
exit 0

And the output:

If this looks a little strange at first don't worry, it gets easier the more you look ...

Get Linux Shell Scripting Bootcamp now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.