The Analogy: The Central Sterile Supply Department and the Operating Theatre
In a large hospital no surgeon assembles their own scalpels, clamps, and retractors from raw steel before each operation. A single department, the Central Sterile Supply Department, prepares standard instrument trays once: a minor-procedures tray, a laparotomy tray, a suture tray. Each tray is checked, sealed, and stored on a labelled shelf. When an operating theatre is set up for a case, the staff draw the trays they need and lay the instruments out on their own table. The theatre does not reinvent a clamp; it borrows a proven, prepared one. That central store of ready-made trays is a library, and this lesson is about building and drawing on one.
Bringing a tray into your theatre is not the same as sending work away, and the difference is the whole point. When you draw a tray, its instruments are now on your table, in your hands, part of this operation -- that is what sourcing a file does. source lib.sh (or its terser spelling . lib.sh) reads the file and runs its lines in your current shell, so every function and variable it defines is now yours to use. Contrast that with sending a specimen to an outside laboratory: you hand it over, the lab works in its own building, and all you get back is a report. Running a file as bash lib.sh is the outside lab -- it works in a separate process and returns only its output and an exit status; nothing it laid on its own table comes back to yours.
A theatre also has a disciplined order of setup, and so does a well-built script. First the safety checks and the count of swabs and sharps -- the shell options, set -euo pipefail. Then the trays are drawn and laid out -- the libraries are sourced. Only then does the procedure itself begin -- the main routine runs -- and finally the theatre is closed down in order. There is one more piece of discipline: a tray that is itself being restocked in the supply department must not accidentally be wheeled straight into an operation. A library file carries the same guard -- a test of whether it was sourced or run directly -- so that being drawn as a tray defines its instruments quietly, while being run on its own does something safe instead of half an operation.
The failures here are quiet, and they are shared, because a sourced file runs in your own process. Draw a tray from the wrong shelf -- source the wrong path, or a stale copy -- and you have the wrong instruments with no warning. Worse, because the tray's instruments are now yours, an instrument that misbehaves harms you directly: a library that calls exit does not end itself, it ends the theatre, terminating the very script that sourced it. A library that quietly flips a theatre-wide setting -- runs set -u, or changes a global -- changes your operation too, often several lines later where the cause is invisible. And drawing the same tray twice can redefine or double what was already laid out. The rest of this lesson is about drawing the right trays, in the right order, with guards that make these quiet failures loud.
Syntax or Core Structure
Sourcing reads a file and executes its contents in the current shell. Anything the file defines -- variables, functions, aliases -- remains defined after the file finishes. Here a small library defines one variable and one function, and the script that sources it uses both as if it had written them itself.
# lib.sh -- a tiny library
GREETING="hello"
say() { echo "$GREETING, $1"; }
# main.sh -- sources the library, then uses what it defines
source ./lib.sh
say "world"
echo "GREETING is now: $GREETING"
Running bash main.sh produces:
Output:
hello, world
GREETING is now: hello
The source keyword (POSIX spells it .) is what makes this work. Had main.sh instead run bash ./lib.sh, the library's say function and GREETING variable would have been defined in a separate child process and thrown away when it exited, leaving say: command not found in the parent. Sourcing is the mechanism behind every shell library, every .bashrc, and every activate-this-environment script you have ever run.
Technical Depth: Where Sourced Code Runs and How to Lay It Out
Sourcing runs in the current shell
The single most important fact about sourcing is that it starts no new process. The lines of the sourced file are read and run by the shell that is already executing, so their side effects -- variables set, directories changed, functions defined -- persist. Running the same file as a command starts a child process whose side effects die with it.
| Behaviour | source f | bash f |
|---|---|---|
| Runs in | current shell | new child process |
| Variables it sets, visible after | yes | no |
| Functions it defines, visible after | yes | no |
| A cd inside it persists | yes | no |
| Stops early with | return | exit |
| Can end the calling shell | yes | no |
This sample proves the top rows. The library sets COLOUR; the driver sets COLOUR=red, then observes it after sourcing and after running.
# setvar.sh
COLOUR="blue"
# compare.sh
COLOUR="red"
source ./setvar.sh
echo "after source: $COLOUR"
COLOUR="red"
bash ./setvar.sh
echo "after bash: $COLOUR"
Output:
after source: blue
after bash: red
Sourcing let setvar.sh reach into the driver and change COLOUR to blue. Running it with bash could not: the child set its own COLOUR and took it to the grave.
return versus exit in a sourced file
Because a sourced file shares your process, exit inside it terminates your shell, not just the file. To stop a sourced file early -- an include guard, a failed precondition -- use return. A bare return outside a function is legal only in a sourced file, and it is exactly the tool for stopping the load.
# guarded.sh
[[ -n "${_GUARDED_LOADED:-}" ]] && return 0 # stop re-loading; do NOT exit
_GUARDED_LOADED=1
Finding the library relative to the script
A script that sources a sibling file cannot assume the caller's working directory. Resolve the script's own directory from ${BASH_SOURCE[0]} and source relative to that:
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/lib/common.sh"
${BASH_SOURCE[0]} is the path of the file currently being read, which stays correct even when that file is itself a sourced library; plain $0 would name the top-level script instead and break a nested library.
The dual-use guard
A file can be both a library (when sourced) and a runnable script (when executed) by testing how it was loaded. When sourced, ${BASH_SOURCE[0]} differs from $0; when run directly the two match.
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@" # runs only when executed directly, never when sourced
fi
Real World Example: A Shared Logging Library and a Deploy Script
Most projects grow a small library of helpers -- logging, error handling, configuration -- that many scripts share. Here is liblog.sh, a logging library with an include guard and a dual-use footer, and deploy.sh, an application script that resolves its own directory, sources the library, and runs a main.
# liblog.sh -- reusable logging helpers.
[[ -n "${_LIBLOG_LOADED:-}" ]] && return 0
_LIBLOG_LOADED=1
log() { printf '%-5s %s\n' "$1" "$2"; }
info() { log "INFO" "$1"; }
warn() { log "WARN" "$1"; }
die() { log "ERROR" "$1"; return 1; }
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
echo "liblog.sh is a library; source it, do not run it"
echo "provides: log info warn die"
exit 2
fi
#!/usr/bin/env bash
# deploy.sh
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/liblog.sh"
APP="checkout"
RELEASES=3
main() {
info "deploying $APP"
local n
for (( n=1; n<=RELEASES; n++ )); do
info "release step $n of $RELEASES"
done
warn "smoke tests skipped"
info "deploy of $APP complete"
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi
Running bash deploy.sh prints:
Output:
INFO deploying checkout
INFO release step 1 of 3
INFO release step 2 of 3
INFO release step 3 of 3
WARN smoke tests skipped
INFO deploy of checkout complete
Running the library directly, bash liblog.sh, prints its usage note and exits with status 2:
Output:
liblog.sh is a library; source it, do not run it
provides: log info warn die
Three pieces of layout do the work. The include guard on the second line of liblog.sh returns immediately if _LIBLOG_LOADED is already set, so sourcing the library twice is harmless -- the second load defines nothing new. The log helper uses printf '%-5s %s\n' to left-pad the level to five columns, which is why INFO and WARN line up in the output. The dual-use footer at the bottom of each file compares ${BASH_SOURCE[0]} with $0: in deploy.sh they are equal when you run it, so main fires; in liblog.sh they are equal only when you run the library by mistake, so it prints guidance and exits rather than defining functions into a shell that will immediately vanish.
The order in deploy.sh is deliberate and worth copying. The shebang names the interpreter; set -euo pipefail turns on strict mode before anything else can fail silently; SCRIPT_DIR is resolved from ${BASH_SOURCE[0]} so the source line works no matter where the caller stood; the library is pulled in; constants (APP, RELEASES) are declared; functions are defined; and only the final guard actually calls main "$@". A reader can scan the file top to bottom and meet every definition before it is used, and a test harness can source deploy.sh to unit-test main without triggering a real deploy, because sourcing makes ${BASH_SOURCE[0]} and $0 differ so the guard stays shut.
The code has real limits, and one is a genuine design flaw. The include guard keys on _LIBLOG_LOADED, a plain global name that lives in the caller's namespace; if any script that sources liblog.sh has already set _LIBLOG_LOADED for an unrelated reason, the guard returns before defining a single function, and the next call to info fails with info: command not found and status 127 -- the whole library silently vanishes with nothing pointing at the cause. A unique, namespaced sentinel such as __LIBLOG_SH_GUARD makes a collision far less likely but does not eliminate it. The second limit is that SCRIPT_DIR uses cd ... && pwd without resolving symlinks; if deploy.sh is invoked through a symlink in a bin directory, ${BASH_SOURCE[0]} is the link's own path and the source looks for liblog.sh beside the link rather than beside the real file, so the deploy dies at startup. Both are layout problems, not logic problems -- which is precisely why a lesson on layout has to name them.
Common Mistakes
- Running a library with
bashwhen you meant to source it.bash lib.shexecutes the file in a child process; the functions and variables it defines are gone the moment it returns. The parent shell then reportscommand not foundfor every helper you expected. Usesource lib.sh(or. lib.sh) so the definitions land in your current shell.
- Calling
exitinside a file that is meant to be sourced. Because a sourced file shares your process,exit 1in a library terminates the script that sourced it, often taking an interactive shell down with it. Usereturnto stop a sourced file; reserveexitfor the top-level script.
- Using
$0to find a library's own directory.$0is the top-level script's path, not the library's, so a sourced helper that computes its directory from$0looks in the wrong place. Use ${BASH_SOURCE[0]}, which is the path of the file currently being read.
- Sourcing with a path relative to the caller's working directory.
source ./lib/common.shonly works if the caller happens to be standing in the right directory. Resolve an absoluteSCRIPT_DIRfirst and source"$SCRIPT_DIR/lib/common.sh"so the script works from anywhere.
- Putting
set -euo pipefailat the top of a sourced library. Those options change the shell that sources you, not just the library. A caller that never asked forset -usuddenly aborts on its own unset variables, several lines later, with no obvious cause. Set strict mode only in top-level scripts.
- Shipping a library with no include guard. Without a guard, sourcing the file twice re-runs its top-level code -- re-declaring functions is harmless, but re-running setup, appending to arrays, or re-registering traps is not. Add a guard that
returns early on the second load.
- Guarding with a plain, collision-prone sentinel name. A guard variable like
LOADEDorINITlives in the caller's namespace; if the caller already uses that name, the guard fires immediately and the library defines nothing. Prefix the sentinel with the library name, for example__MYLIB_SH_LOADED.
- Defining library functions that quietly write global variables. A helper that sets
resultoriwithoutlocalclobbers a variable of the same name in the caller. Declare every internal variablelocal, and document any global your library deliberately exports.
- Assuming a sourced file's failure is noticed.
source config.shthat fails part-way still returns to the caller; unless the caller checks the status or runs underset -e, a broken config is used as if it loaded cleanly. Check the return status of a source that can fail, or let strict mode catch it.
Best Practices
- Write the file as a library first. Define functions and constants at the top level, and put nothing that does work outside a function except the include guard.
- Guard against double-sourcing with a namespaced sentinel. Open each library with
[[ -n "${__MYLIB_LOADED:-}" ]] && return 0so sourcing it twice is always safe.
- Resolve the script's own directory once. Compute
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"at the top and source everything relative to it.
- Make dual-use files explicit. End them with
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then main "$@"; fiso the file can be sourced for its functions or executed as a command.
- Keep strict mode in top-level scripts only. Never let a sourced library run
set -euo pipefailand change the caller's shell options behind its back.
- Follow one fixed layout order. In every script: shebang, strict mode, directory resolution, sourced libraries, constants, functions, then the
mainguard.
- Treat the caller's namespace as someone else's property. Declare internal variables
localinside library functions and document any global you deliberately export.
- Fail loudly when a library is run directly. Print a short usage note and exit non-zero so a mistaken
bash lib.shis obvious instead of silent.
Practice Exercises
- Split and source. Take a script you have written that mixes helpers and logic. Move its helper functions into
lib.sh, add an include guard, and have the original script resolveSCRIPT_DIRand source the library. Confirm the script still runs identically from three different working directories.
- Prove the process boundary. Write
setdir.shthat runscd /tmpand defines a functionwhere. Source it from one driver and run it withbashfrom another. Show that after sourcing your working directory changed andwhereexists, and afterbashneither did, and explain the one-line reason.
- Build a dual-use file. Write
greet.shthat definesgreet nameand, when run directly, callsgreet "$1", but when sourced definesgreetonly. Demonstrate both modes and show that sourcing it does not print anything.
- Break the include guard on purpose. Using the
liblog.shfrom this lesson, set_LIBLOG_LOADED=1in a caller before sourcing, then callinfo. Capture thecommand not foundfailure and its status, then rename the sentinel to a namespaced form and show the library now loads. Write two sentences on why the original name was a latent bug.