Wednesday, November 21, 2012

Debugging Shell Scripts in Unix

Debugging is an important part of your overall development process. Unfortunately not many developers know that even shell scripts can be debugged. The good thing is debugging shell scripts is just about knowing a few options of the 'sh' command. Lets see how we can debug the shell scripts.

To see exactly where the script produces an error use the 'sh' command with a 'x' option:

sh -x myscript.sh your-arguments-if-you-hahve

When you run the above command you can see each statement with their output printed in the next line.

For example if i have a script which does addition of two numbers given by the user like:

#!/bin/sh
echo $1
echo $2
echo $(($1 + $2))

The output of 'sh -x myscript.sh 3 4' would be

+ echo 3
3
+ echo 4
4
+ echo 7
7

So, we see the statement and its output in the next line.

Other options are:

-e in non-interactive mode, exit immediately if a command fails.

-v print shell input lines as they are read.

-n read commands but do not execute them.

In the other options 'v' is probably a really good option to explore. If i run my above script with '-v' option then the following output would be seen:

sh -v myscript.sh 3 4

#!/bin/sh
echo $1
3
echo $2
4
echo $(($1 + $2))
7

This is again a good option to explore.