Bash Include Guard
When building a set of interdependent shell scripts, it becomes necessary to use the equivalent of a C/C++ "include guard" to ensure that common scripts do not get sourced more than once. The solution is actually pretty simple.
Stick this near the top of your bash script:
[ -n "$LIB_NAME" ] && return || readonly LIB_NAME=1
Use some unique name instead of LIB_NAME</code>. For example:
bash-3.2$ cat my_lib.sh
[ -n "$_MY_LIB" ] && return || readonly _MY_LIB=1
echo "HELLO!"
bash-3.2$ source my_lib.sh
HELLO!
bash-3.2$ source my_lib.sh
bash-3.2$
Written by Matthew Tardiff
Related protips
1 Response
Nice! Thanks for the tip.
I might recommend one small change. Using a semicolon makes it easier to read (in my opinion) and helps it pass ShellCheck.
[ -n "$LIB_NAME" ] && return; readonly LIB_NAME=1
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Shell
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#