Debugging Shell Scripts

by mike on May 5, 2011

There are a lot of possibilities for making errors when you are writing shell scripts. It is easy to make a typo, forget a backtic, or a curly brace. Debugging is when you attempt to correct bugs in a program or script. It is not always an easy process. “Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. ” (Brian Kernighan)

The shell has the “-x” option that will help you debug your script. This option will make the shell display each command before it runs. Each command is preceded with the PS4 variable “+” so it is easier to distinguish the debugging output from the command.

sh -x daily.sh
++ date +%Y%m%d_%H%M%S
+ TIMESTAMP=20100817_044750
+ echo 20100817_044750
20100817_044750
+ DIR=/home/daily_20100817_044750
+ mkdir /home/daily_20100817_044750
++ find /root/scripts -iname '*.sh' -mtime -1
+ for SCRIPT in '`find /root/scripts -iname '\''*.sh'\'' -mtime -1`'
+ '[' -f /root/scripts/while3.sh ']'
+ cp /root/scripts/while3.sh /home/daily_20100817_044750/
+ echo '/root/scripts/while3.sh is backed up to /home/daily_20100817_044750'
/root/scripts/while3.sh is backed up to /home/daily_20100817_044750
+ for SCRIPT in '`find /root/scripts -iname '\''*.sh'\'' -mtime -1`'
+ '[' -f /root/scripts/dir.sh ']'
+ cp /root/scripts/dir.sh /home/daily_20100817_044750/
+ echo '/root/scripts/dir.sh is backed up to /home/daily_20100817_044750'
/root/scripts/dir.sh is backed up to /home/daily_20100817_044750
+ for SCRIPT in '`find /root/scripts -iname '\''*.sh'\'' -mtime -1`'
+ '[' -f /root/scripts/loop.sh ']'
+ cp /root/scripts/loop.sh /home/daily_20100817_044750/
+ echo '/root/scripts/loop.sh is backed up to /home/daily_20100817_044750'
/root/scripts/loop.sh is backed up to /home/daily_20100817_044750
+ for SCRIPT in '`find /root/scripts -iname '\''*.sh'\'' -mtime -1`'
+ '[' -f /root/scripts/keystroke.sh ']'
+ cp /root/scripts/keystroke.sh /home/daily_20100817_044750/
+ echo '/root/scripts/keystroke.sh is backed up to /home/daily_20100817_044750'
/root/scripts/keystroke.sh is backed up to /home/daily_20100817_044750
+ for SCRIPT in '`find /root/scripts -iname '\''*.sh'\'' -mtime -1`'
+ '[' -f /root/scripts/perm.sh ']'


You can change the PS4 variable by exporting it to that shell.

export PS4='>>'

sh -x daily.sh

>>>date +%Y%m%d_%H%M%S
>>TIMESTAMP=20100817_050908
>>echo 20100817_05090820100817_050908
>>DIR=/home/daily_20100817_050908
>>mkdir /home/daily_20100817_050908
>>>find /root/scripts -iname '*.sh' -mtime -1

—cut—

 

 

In addition, you can set the “-x” option in the shell for debugging by placing it in the script at the start of the script.

set -x
To turn it of use:
set +x

Or you can use xtrace, on:
set -o xtrace

To turn off:
set +o xtrace

Comments on this entry are closed.

Previous post:

Next post: