2025-11-07    2025-11-07    256 字  1 分钟

The note is generated by “ChatGPT”.

🔹 source

  • Executes a script in the current shell environment.
  • Does not create a new shell process.
  • All variable exports, alias definitions, and PATH modifications remain active after execution.
  • Commonly used for reloading configuration files (e.g., source ~/.bashrc).
  • Bash and Zsh built-in command.

Example:

1
source ~/.bashrc

→ Reloads your Bash configuration immediately in the current session.


🔹 bash

  • Starts a new Bash subshell to run the script.
  • The parent shell does not inherit any environment changes.
  • Safer for running scripts that should not affect your current session.
  • Suitable for installation, automation, or isolated execution.

Example:

1
bash install.sh

→ Runs the script, but changes (like export PATH=...) disappear when it exits.


🔹 .

  • A POSIX-standard alias for source.
  • Works in all POSIX-compliant shells (e.g., sh, dash, bash, zsh).
  • Functionally identical to source.

Example:

1
. ~/.bashrc

→ Same as source ~/.bashrc, but more portable across shells.


âš™ī¸ Comparison Table

CommandRuns in Current ShellCreates SubshellPersists Env ChangesPortability
source script.sh✅ Yes❌ No✅ YesBash/Zsh only
. script.sh✅ Yes❌ No✅ YesPOSIX (universal)
bash script.sh❌ No✅ Yes❌ NoBash only

🧠 Quick Example

1
2
3
# test.sh
export MYVAR="Hello"
echo "Inside script: $MYVAR"

Run it two ways:

1
2
bash test.sh     # MYVAR not available after run
source test.sh   # MYVAR stays in current shell

✅ Key Takeaway

  • Use bash when you want isolation.
  • Use source or . when you want persistent changes in your shell session.