Debug Shell Scripts

From Exterior Memory
Jump to: navigation, search

In order to debug shell scripts, the following two tricks are useful.

Trace all commands

To print each command as it is executed, use the following command at the start of your script:

set -x

Redirect STDOUT and STDERR

In case the script is called from another process, you can not see it's output (including useful errors to STDERR). In order

logfile=/tmp/shellscript.log
exec 2> $logfile   # redirect STDERR to $logfile
exec 1>&2          # redirect STDOUT to STDERR, so it also ends up in $logfile

Combined Result

In case you want to do things very proper, you should also restore the STDOUT and STDERR file descriptors.

#!/bin/sh

logfile=/tmp/logfile.txt
exec 5>&1       # Save STDOUT (#1) descriptor in #5
exec 6>&2       # Save STDERR (#2) descriptor in #6
exec 2> $logile # Redirect STDERR to logfile
exec 1>&2       # Redirect STDOUT to STDERR
set -x          # turn trace on

# ... your script goes here ...

set +x          # turn trace off
exec 1>&5       # Restore STDOUT
exec 2>&6       # Restore STDERR
exit 0