Running bash shell scripts in debug mode to trace execution

This is so handy, I can’t believe i’ve never used or even heard of this until today! You can easily run your bash shell scripts in debug mode to watch what they’re doing behind the scenes in real time. You get to see the levels of nesting when you’re inside loops and variables get replaced with their actual contents at the time of execution.

This shell script:

# add usb drive mount point
echo
echo “USB DRIVE MOUNT”
echo “+ Checking for /mnt/usbdrive”
if [ -d /mnt/usbdrive ]; then
echo ” - directory already exists - nothing to do”
else
echo ” - Creating usbdrive directory”
sudo mkdir -p /mnt/usbdrive
fi

if [ -d /mnt/usbdrive ]; then
exit 0
else
exit 1
fi

Turns into this:

+ echo

+ echo ‘USB DRIVE MOUNT’
USB DRIVE MOUNT
+ echo ‘+ Checking for /mnt/usbdrive’
+ Checking for /mnt/usbdrive
+ ‘[' -d /mnt/usbdrive ']‘
+ echo ‘ - directory already exists - nothing to do’
- directory already exists - nothing to do
+ ‘[' -d /mnt/usbdrive ']‘
+ exit 0

To run the “do_something.sh” script in debug mode, run it like this:

[thisguy@localhost ~]$ bash -x do_something.sh

This might come in handy if you have multiple levels of nesting in ‘for’ and ‘while’ loops or a few if/then/else statements and you want to see just what is getting passed in the comparisons. Consider a simple thing such as this:

#!/bin/sh
WHOAMI=`whoami`
if [[ $WHOAMI != root ]]; then
  echo "Please run this as root --> $ sudo $0"
  exit 1
fi

You get to see just what the $WHOAMI variable is getting assigned.

++ whoami
+ WHOAMI=thisguy
+ [[ thisguy != root ]]
+ echo 'Please run this as root --> $ sudo go1.sh'
Please run this as root --> $ sudo go1.sh
+ exit 1
Posted by admica   @   26 August 2009

Related Posts

0 Comments

No comments yet. Be the first to leave a comment !
Leave a Comment

Name

Email

Website

Previous Post
« Assembly Basics, hello world!
Next Post
Cybercrime Investigations into foreign ISPs »
Powered by Wordpress   |   Lunated designed by ZenVerse