Shell Library Design
Library Guard
Load Once
Shell libraries often protect setup code with a guard flag. The guard makes repeated loading predictable by running initialization only once.
Program
Play the script to choose the guard state and see whether setup runs.
library_guard_flag.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash
library_loaded=0
if [[ "$library_loaded" -eq 0 ]]; then
library_loaded=1
status="loaded"
else
status="already-loaded"
fi
echo "$status"
#!/usr/bin/env bash
library_loaded=1
if [[ "$library_loaded" -eq 0 ]]; then
library_loaded=1
status="loaded"
else
status="already-loaded"
fi
echo "$status"
library_loaded ← 0
3library_loaded=04if [[ "$library_loaded" -eq 0 ]]; thenvalues this step0library_loadedif [[ "$library_loaded" -eq 0 ]]; then
3library_loaded=04if [[ "$library_loaded" -eq 0 ]]; then5 library_loaded=1values this step0library_loadedlibrary_loaded ← 1
4if [[ "$library_loaded" -eq 0 ]]; then5 library_loaded=16 status="loaded"values this step1library_loadedstatus ← loaded
5 library_loaded=16 status="loaded"7elsevalues this steploadedstatusecho "$status"
9fi10echo "$status"outputloadedvalues this steploadedstatus
library_loaded ← 1
3library_loaded=14if [[ "$library_loaded" -eq 0 ]]; thenvalues this step1library_loadedif [[ "$library_loaded" -eq 0 ]]; then
3library_loaded=14if [[ "$library_loaded" -eq 0 ]]; then5 library_loaded=1values this step1library_loadedstatus ← already-loaded
7else8 status="already-loaded"9fivalues this stepalready-loadedstatusecho "$status"
9fi10echo "$status"outputalready-loadedvalues this stepalready-loadedstatus
guard flag
A guard flag records whether setup has already run.
idempotent load
Idempotent loading means repeated loads do not repeat setup work.
library setup
Library setup should be explicit and easy to skip when it has already happened.