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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.