#!/usr/bin/env bash
# ===== Sourced Preamble =====================================
# This part runs whether the script is sourced OR executed.
# Perfect for setting aliases, exports, or functions.
my_shared_function() {
echo "Function is loaded!"
}
export SHARED_VAR="Hello World"
# --- Source/Exec Boundary -----------------------------------
return 0 2>/dev/null
# --- removed the redirect if rendering error is important ---
# we dont want this in a sourced script unless we want the
# executing shell to "exit on error" (which is unexpected when interactive)
set -eo pipefail
# ===== Direct Execution Only ================================
# Sourced environments will never see this.
# Executed environments ignore the return error and continue.
echo "This script was executed directly, not sourced."
my_shared_function
- When Sourced: Bash evaluates return 0. Since it is being sourced, return is a valid command. The script stops processing immediately and returns control to the parent shell. Zone 2 is ignored. [1, 2, 3, 4]
- When Executed Directly: Bash evaluates return 0. Because it is not inside a function or sourced script, this is invalid syntax. Bash throws an error, but the 2>/dev/null silences it. The script then safely drops down into Zone 2 and runs the rest of the file. [5, 6, 7]