Debug Linux shell scripts with ‘-x’

If you ever need to debug a Unix or Linux shell script, you can just add the -x option to the interpreter when you invoke it. You can add the shell's debug option on the command line like this:

sh -x

or at the end of the first line in your shell script (the she-bang line), like this:

#!/bin/sh -x

I was just working on a shell script related to fonts on a Mac OS X (Unix), system, and when I tried to run it normally, all it gave me was this error message:

$ sh line 41: syntax error: unexpected end of file

To help debug the script, I added the -x option, and got the following debug output:

$ sh -x

+ DIR=/Library/Fonts
+ IFS='
+ FILE=fonts.html
+ FONTFILE=fonts2
+ echo '<html><head>' line 41: syntax error: unexpected end of file

This may not look like a tremendous help in solving the problem, but the error in my shell script was on the line just after the last one that was printed in the debug output, which was actually line eight of my shell script. So, if the debugger didn't point me directly to my syntax error, at least it pointed me in a much closer direction.