Debugging Shell Scripts

If you write shell scripts of any complexity at all, sooner or later bugs are going to creep in. Although there is no full-fledged debugger for the shell, it does provide some primitive debugging capabilities in the form of being able to trace each action that is performed. You turn on the tracing by adding -xv to the end of the #!/bin/sh line in your script, so it looks like this:

#!/bin/sh -xv

This works best if you pipe the output to more or less, and also if you redirect both STDOUT and STDERR to the same place so that you can see both the output of the script and the errors. Here is a simple example:

 #!/bin/sh -xv # Demonstrate the use of tracing in shell script debugging result=`echo "2 * 12 / (2 + 2)` | bc` echo ...

Get FreeBSD® Unleashed 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.