Debug Sections of a Script

by mike on May 2, 2011

You do not have to debug the whole script, you can just debug the sections giving you the most difficulties. In this example, “set -x” and “set +x” encompass the section that you want to debug. The output shows how this section is sent to screen while the rest of the script functions normally.

#!/bin/bash
TIMESTAMP=`date +%Y%m%d_%H%M%S`;
echo $TIMESTAMP
DIR=/home/daily_$TIMESTAMP;
mkdir $DIR
set -x
for SCRIPT in `find /root/scripts -iname '*.sh' -mtime -1`
do
if [ -f $SCRIPT ]
then
cp $SCRIPT $DIR/
set +x
echo "$SCRIPT is backed up to $DIR"
fi
done

sh daily.sh
20100819_202608
++ find /root/scripts -iname '*.sh' -mtime -1
+ for SCRIPT in '`find /root/scripts -iname '\''*.sh'\'' -mtime -1`'
+ '[' -f /root/scripts/daily.sh ']'
+ cp /root/scripts/daily.sh /home/daily_20100819_202608/
+ set +x
/root/scripts/daily.sh is backed up to /home/daily_20100819_202608

The “-v” option prints shell input lines as they are read. This is the verbose option. Here is an example of the same script with “-xv” set to provide additional information.

#!/bin/bash
TIMESTAMP=`date +%Y%m%d_%H%M%S`;
echo $TIMESTAMP
DIR=/home/daily_$TIMESTAMP;
mkdir $DIR
set -xv
for SCRIPT in `find /root/scripts -iname '*.sh' -mtime -1`
do
if [ -f $SCRIPT ]
then
cp $SCRIPT $DIR/
set +xv
echo "$SCRIPT is backed up to $DIR"
fi
done

sh daily.sh
20100819_203413
for SCRIPT in `find /root/scripts -iname '*.sh' -mtime -1`
do
if [ -f $SCRIPT ]
then
cp $SCRIPT $DIR/
set +xv
echo "$SCRIPT is backed up to $DIR"
fi
done
find /root/scripts -iname '*.sh' -mtime -1
++ find /root/scripts -iname '*.sh' -mtime -1
+ for SCRIPT in '`find /root/scripts -iname '\''*.sh'\'' -mtime -1`'
+ '[' -f /root/scripts/daily.sh ']'
+ cp /root/scripts/daily.sh /home/daily_20100819_203413/
+ set +xv
/root/scripts/daily.sh is backed up to /home/daily_20100819_203413

One additional option that is available is the “-f” which turns off using metacharacters or globbing. With this option enabled commands like “ls /etc/*” do not produce output as globbing will not work.

{ 1 comment }

Brian Snipes May 3, 2011 at 3:09 pm

Thank you! That sure beats remarks and echos for debugging.

Comments on this entry are closed.

Previous post:

Next post: