Monday, March 10, 2008

Easy Debugging for Shell Scripts

To fix things that aren't working, I want to know where and when they failed.

Here's how you can get that information for shell scripts, without much work:
$ cat timestamps.sh
# timestamps.sh -- turn on command timestamping

timestamps() {
if [ "$1" = "off" ]
then
set +x
else
PS4='== $(date)\n'
set -x
fi
}

$ cat example
#!/bin/bash

source timestamps.sh

timestamps on
echo hello
timestamps off
echo goodbye
$ ./example 2>/dev/null
hello
goodbye
$ ./example
=== Mon Mar 10 06:55:06 MDT 2008
echo hello
hello
=== Mon Mar 10 06:55:06 MDT 2008
timestamps off
=== Mon Mar 10 06:55:06 MDT 2008
'[' off = off ']'
=== Mon Mar 10 06:55:06 MDT 2008
set +x
goodbye
This trick has nice features:
  1. All commands are printed out before they're executed.
  2. Each command is timestamped, so you know when it's executed. (This helps when you're logging.)
  3. All the debug information is sent to stderr; you can get rid of it and just see normal output with 2>/dev/null
  4. You can choose sections of your code to track or ignore.
  5. It's a trivial amount of code: a pauci-line module, and a single line added to your script.

No comments: