The safe_source.lib.sh library provides a robust and reusable mechanism to temporarily source Bash scripts and fully revert any changes made to the shell environment. This includes environment variables, functions, aliases, and exported variables.
- Full Environment Snapshot: Captures variables, functions, aliases, and exports before sourcing.
- Safe Sourcing and Reversion: All changes are isolated and reversible.
- Nested Support: Multiple scripts can be sourced and unsourced independently (stack-based).
- Minimal Side Effects: Reverts exactly what changed—nothing more, nothing less.
- Reusable as a Library: Designed to be included in any Bash script.
source /path/to/safe_source.lib.shSafely source another script, taking a snapshot of your current shell environment.
safe_source ./config.shRevert changes made by the last script sourced using safe_source.
safe_unsourcea.sh:
export VAR_A="from A"
alias hello_a='echo Hello from A'
function greet_a() { echo "Greet from A"; }b.sh:
export VAR_B="from B"
alias hello_b='echo Hello from B'
function greet_b() { echo "Greet from B"; }#!/usr/bin/env bash
source ./safe_source.lib.sh
safe_source ./a.sh
safe_source ./b.sh
echo "${VAR_A}"
echo "${VAR_B}"
hello_a
hello_b
greet_a
greet_b
safe_unsource # removes b.sh effects
safe_unsource # removes a.sh effects- After sourcing
a.shandb.sh, all functions, aliases, and variables are available. - After calling
safe_unsourcetwice, none of the sourced script elements remain.
-
Invalid paths produce:
Error: Script './missing.sh' does not exist. -
Calling
safe_unsourcewith no stack:Error: No environment snapshot to unsource.
- Temporary Files:
- Used in
/tmpto snapshot the environment. Auto-cleaned during unsourcing.
- Used in
- Safe to Source Multiple Times:
- Guards prevent reloading and redefining the library or functions.
- Fallback Logging:
- If
info,error,warn, etc. are not defined, they’re created as basic echo-style functions.
- If
This script is provided under the MIT License. Feel free to use and modify it for your needs.
Happy Sourcing! 🚀