Bash Script Sourcing Pattern with Isolated Exit Codes

Bash Script Sourcing Pattern with Isolated Exit Codes

Problem: Need to access functions defined in .bashrc (not exported with export -f) while allowing scripts to use exit without terminating the calling shell.

Solution: Source the script in a subshell: (source script.sh)

Implementation

Parent Script (scratch1.sh)

#!/bin/bash

foo123() {
  echo "foo1 that is defined in scratch 1"
}

main() {
  (source /path/to/scratch2.sh) || {
    throw "Scratch 2 failed"
  }
  echo.green "end in scratch 1"
}

main "${@}" || exit 1

Child Script (scratch2.sh)

#!/bin/bash

main() {
  foo123  # Can call parent's functions
  echo.red "exiting in scratch2"
  exit 1  # Only exits the subshell
}

main "${@}" || exit 1

How It Works

  • () creates a subshell that inherits parent functions
  • exit in child only terminates the subshell
  • || catches the exit code for error handling

Benefits

  • Access to non-exported functions
  • Safe exit handling
  • Clean error propagation
  • Normal script semantics

Use Cases

  • Quick scripts using shell convenience functions
  • Development/prototyping
  • Legacy integration where functions aren't exported