Thursday, August 20, 2009

Include Guards in Sourced Files

How do I keep from sourcing the same files over and over?

My shell scripts often have lines like this:
source gripe.sh
Unfortunately, so do other sourced files. How do I keep from sourcing something more than once?

In C programs, my include files handle this with constructs like this:
// foo.h -- include file for foo definitions
#ifndef _FOO_H
#define _FOO_H
...
#endif
The first time foo.h is included, it grabs all the included information. If it's accidentally included a second time, though, _FOO_H is already defined, so the file is skipped.

Here's an analogous construct that I use at the top of shell "include" files.
# include guard
if [ ${_gripe_version:-0} -gt 0 ]
then
return 0
else
_gripe_version=1
fi
... # remainder of file
I could put the file contents inside the else block, and the fi at the end of the file, but I like just clumping the whole thing at the top.

No comments: