Simple Bash Debugging: set -{x,u,n}

The bash shell gets more negative press than it deserves from most “real” programmers. Between the “I can’t see what it’s doing, I need an echo after nearly every line!” and the “Why doesn’t it have a check option like perl’s -c!?” most people that only occasionally dip in to bash end up frustrated by it’s lack of features. All because they can’t be bothered to read the man page…

I’m going to show you three simple bash “tricks” that’ll make your script debugging a lot easier; and none of them require that much searching to find!. Each of the three tidbits presented can be used in one of two ways, they can either be placed one to a line near the top of your shell scripts, just under the shebang line like this, ‘set -x’, or they can be used as command line arguments to bash itself (bash -x

First up we have the ‘-x’ option. This provides a simple trace of each and every command executed by the shell script, it also shows the interpolated values of the variables; which can save a lot of echo’s and printf’s!

Next up we have ‘-n’, the syntax checker. When this is specified the script doesn’t actually run but instead has it’s syntax checked for any errors. This removes the annoying “String not terminated” messages that you’ll occasionally get from not terminating your strings. Only when ‘-n’ is specified you don’t run half a script, leaving the system in an inconsistent state.

The last of our time-savers is the ‘-u’ option, this forces any undefined variables to terminate the script rather than carry on with no values. Although this is often useful, and saves you backtracking through the output of ‘-x’ to find the undeclared value, you can’t combine it with the ‘-n’ option. You have to allow the script to run in order for the undefined values to be detected; while this is less than ideal it’s better than nothing…

I hope these three lesser known bash features make your scripting more enjoyable and productive, I’ve lost count of the time they’ve saved me!