TL;DR
Sourcing a script (source filename or . filename) runs the commands in that file within your *current* shell environment, meaning any variables it sets or functions it defines will persist after the script finishes. Executing a script (./filename or bash filename) runs the commands in a *new* subshell. This isolation makes executing generally safer because changes to the environment are contained.
Why Sourcing is Riskier
- Environment Changes Persist: When you source a script, it directly modifies your current shell’s state. If the script contains malicious code that sets unwanted variables or alters important settings (like
PATH), those changes remain active in your session.- Example of a dangerous sourced script:
echo 'export PATH=$PATH:/some/malicious/directory' >> ~/.bashrc; source ~/.bashrcThis adds a malicious directory to your
PATH, potentially allowing an attacker to execute their own programs instead of legitimate ones.
- Example of a dangerous sourced script:
- Function Definitions: Sourced scripts define functions in your current shell. A compromised script could introduce harmful functions.
- Example:
function ls { /some/malicious/script; command ls}This overwrites the standard
lscommand with a malicious version.
- Example:
- Accidental Overwrites: Sourcing can easily overwrite existing variables or functions without warning.
Why Executing is Generally Safer
- Subshell Isolation: When you execute a script, it runs in a separate subshell process. Any changes made to the environment within that subshell are isolated and do not affect your current shell.
- Example:
./script.shChanges inside
script.shwon’t alter your main shell’s variables or functions.
- Example:
- Limited Impact: Even if a script contains malicious code, the damage is typically limited to the subshell process.
- Clean Exit: When the script finishes, the subshell terminates, and all its changes are discarded. Your current shell remains unaffected.
Practical Steps for Safe Script Handling
- Always Review Scripts Before Sourcing: Carefully examine any script you intend to source before running it. Understand what each command does.
- Prefer Executing Over Sourcing: Unless you specifically need the script to modify your current shell environment, execute scripts instead of sourcing them.
- Use a Virtual Environment (where appropriate): For complex projects or when dealing with untrusted code, consider using a virtual environment to isolate dependencies and prevent conflicts.
- Check File Permissions: Ensure that the script has appropriate permissions. It should not be writable by other users.
- Example:
chmod 755 filenameThis sets read, write and execute permission for the owner, and only read and execute for group and others.
- Example:
- Be Wary of Scripts from Untrusted Sources: Avoid sourcing or executing scripts from unknown or untrusted sources.

