Skip to content

Instantly share code, notes, and snippets.

@dweomer
Last active July 15, 2026 20:22
Show Gist options
  • Select an option

  • Save dweomer/65b6a16c8a90713bd7eaf0858fb2abcf to your computer and use it in GitHub Desktop.

Select an option

Save dweomer/65b6a16c8a90713bd7eaf0858fb2abcf to your computer and use it in GitHub Desktop.
scripting tricks

RETURN EARLY WHEN SOURCED

#!/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

The Mechanics

  • 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]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment