Shell Script Debugging

I was wanting to set a debugging option in a script where the commands would get printed out instead of being executed. At the moment I have every command in an 'if' statement...

if [ $debugOn ] ; then
debugmessage touch $target/test
else
touch $target/test
fi

There must be a better way to do this 🙂

Any suggestions?

Ta.
-david

Server 10.4.8

Posted on Feb 17, 2007 10:39 AM

Reply
5 replies

Feb 17, 2007 11:48 AM in response to Ken Nellis

That's a usefull one to know for tracing through the whole script, thanks!

However, I was looking for something whereby I can selectively control what get printed out. Also, I don't actually want to run some of the commands in the script, just print out what 'would' have run. The 'set -x' still actually proceeds and executes the various script statements.

I've so far got a slightly better version...

debugmessage() { if [ $debugOn ] ; then
echo "$@"
else
$@
fi
}

Then, I can have the following command in the script...

debugmessage rm -rf $dir

and if debug is on, it will not actually run the 'rm' command, just print it out.

However, the above gives me an error... "line 34: debug:: command not found", which relates to the line after the 'else' with "$@" on it

Almost there but possibly a much better way?

Ta.
-david

Feb 19, 2007 8:08 AM in response to David_x

Hello,

You might want to look at the getopts function:
<pre style="overflow: auto;font-size:small; font-family: Monaco, 'Courier New', Courier, monospace; color: #222; background: #ddd; padding: .3em .8em .3em .8em; font-size: 10px;">DEBUG=0

while getopts 'd' option ; do
case "$option" in

'd')
DEBUG=1
;;

?)
usage # (function that prints help message for unknow options)
exit 0
;;
esac
done
shift `expr $OPTIND - 1`</pre>
Then for debug mode:
your_script -d

--
Cole


15 PB Mac OS X (10.3.9)

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Shell Script Debugging

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.