Last Updated: June 24, 2021
·
3.577K
· themattrix

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$

1 Response
Add your 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 ·