Linux Shell Scripting Tutorial (LSST) v1.05r3
Prev
Chapter 3: Shells (bash) structured Language Constructs
Next

How to de-bug the shell script?

While programming shell sometimes you need to find the errors (bugs) in shell script and correct the errors (remove errors - debug). For this purpose you can use -v and -x option with sh or bash command to debug the shell script. General syntax is as follows:
Syntax:
sh   option   { shell-script-name }
OR
bash   option   { shell-script-name }
Option can be
-v Print shell input lines as they are read.
-x After expanding each simple-command, bash displays the expanded value of PS4 system variable, followed by the command and its expanded arguments.

Example:

$ cat > dsh1.sh
#
# Script to show debug of shell
#
tot=`expr $1 + $2`
echo $tot

Press ctrl + d to save, and run it as
$ chmod 755 dsh1.sh
$ ./dsh1.sh 4 5

9
$ sh -x dsh1.sh 4 5
#
# Script to show debug of shell
#
tot=`expr $1 + $2`
expr $1 + $2
++ expr 4 + 5
+ tot=9
echo $tot
+ echo 9
9

See the above output, -x shows the exact values of variables (or statements are shown on screen with values).

$ sh -v dsh1.sh 4 5

Use -v option to debug complex shell script.


Prev
Home
Next
The case Statement
Up
Advanced Shell Scripting