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_loaded
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"
  1. library_loaded ← 0

    3library_loaded=04if [[ "$library_loaded" -eq 0 ]]; then
    values this step0library_loaded
  2. if [[ "$library_loaded" -eq 0 ]]; then

    3library_loaded=04if [[ "$library_loaded" -eq 0 ]]; then5    library_loaded=1
    values this step0library_loaded
  3. library_loaded ← 1

    4if [[ "$library_loaded" -eq 0 ]]; then5    library_loaded=16    status="loaded"
    values this step1library_loaded
  4. status ← loaded

    5    library_loaded=16    status="loaded"7else
    values this steploadedstatus
  5. echo "$status"

    9fi10echo "$status"
    outputloaded
    values this steploadedstatus
  1. library_loaded ← 1

    3library_loaded=14if [[ "$library_loaded" -eq 0 ]]; then
    values this step1library_loaded
  2. if [[ "$library_loaded" -eq 0 ]]; then

    3library_loaded=14if [[ "$library_loaded" -eq 0 ]]; then5    library_loaded=1
    values this step1library_loaded
  3. status ← already-loaded

    7else8    status="already-loaded"9fi
    values this stepalready-loadedstatus
  4. echo "$status"

    9fi10echo "$status"
    outputalready-loaded
    values 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.