Debugging Scripts

A script that is executed by an application or another script is failing. Executing the script manually doesn’t provide more clues since it’s only failing when invoked by another program. Also, you don’t want to redirect the output of the script each time you execute it. And you want to see more debugging information like line numbers.

Adding the following lines at the beginning of the script will help:

export PS4='$0.$LINENO+ '
exec > /tmp/script.log
exec 2>&1
set -x

Example:

$ cat test
#!/bin/bash
export PS4='$0.$LINENO+ '
exec > /tmp/script.log
exec 2>&1
set -x
ls -ld /etc
ls -ld /boot
echo "This is a test"
$ ./test
$ cat /tmp/script.log
./test.6+ ls -ld /etc
drwxr-xr-x 83 root root 7512 2006-07-22 16:49 /etc
./test.7+ ls -ld /boot
drwxr-xr-x 5 root root 1960 2006-07-22 15:30 /boot
./test.8+ echo 'This is a test'
This is a test
$

These lines will turn on debugging and all information will be redirected to the log file. So you won’t have to redirect the output each time you run the script, e.g. “./script > /tmp/script.log 2>&1″. In some cases you can’t do that if the script is invoked by an application.

The PS4 builtin shell variable describes the prompt seen in debug mode. The $0 variable stands for the name of the script file itself. $LINENO shows the current line number within the script. The exec command redirects I/O streams. The first exec command redirects stdout stream 1 to /tmp/script.log. 2>&1 redirects stderr stream 2 to stdout stream 1. And “set -x” enables debugging.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: