Terminal · intermediate

Sourcing vs subprocess execution

Sourcing reads commands into the current shell environment, while executing a script normally runs it in a separate process and cannot directly modify the parent's shell state.

Why it matters

The choice determines whether directory changes, functions, options, and variables persist after the file finishes.

Mental model

How to reason about sourcing vs subprocess execution

source is textual execution inside the current shell context; ordinary execution creates a child with inherited initial state whose later changes remain isolated.

Analogy

Sourcing lets a contractor rearrange your current room, while subprocess execution gives them a copied workspace whose rearrangement does not alter yours.

Examples

See the boundary, not just the happy path

Worked example · Load shell definitions

. ./env.sh

The POSIX dot command evaluates env.sh in the current shell, so variable assignments and function definitions can remain afterward.

Worked example · Isolate a temporary directory change

(cd build && make package)

Parentheses create a subshell environment, so its cd does not change the outer shell's working directory.

Useful contrast · Executed script state is isolated

./set-env.sh

Even if the child script exports a variable, it changes only its own environment and that of its descendants, not the already-running parent shell.

Common mistakes

Misconceptions to remove early

Sourcing untrusted content

Sourced text executes with the current shell's permissions and can alter its state, so treat it as code rather than a passive configuration format.

Using exit in a sourced helper

exit can terminate the caller's shell; a sourced file intended as a library should normally return or structure failures for its calling context.

Quick check

Can you predict the result?

1. Which form can intentionally define a function in the current shell?
  • . ./functions.sh
  • ./functions.sh
  • sh functions.sh
Answer: . ./functions.sh
2. Why does (cd /tmp; work) leave the outer shell's directory unchanged?
Answer: The directory change occurs in a subshell environment rather than the outer shell.

Keep building

Authoritative references

Make the idea retrievable.

Study this concept with spaced repetition, next to the commands where you use it.

Get Terminaster