Bash: Why would sourcing a file be less safe than bashing it (executing in another session)?

Is it the case, or I completely misunderstood?

I've heard in the the context of sourcing a sub-script from a master-script. For example, you curl and source remote script which sources one or more script (for the sake of the question let's assume that all of these scripts are safe and okay).

What I try to understand is why would someone think it's less safe to source the internal script, rather then running it (~/sub-script.sh or bash ~/sub-script.sh).

If this entire question sounds unlikely or absurd please don't be sarcastic, but please do make sure to vote to close it if you can as it might just be based of a misunderstanding from my side, or a misphrasing of some deeper intention of the man that said that.

2 Answers 2


I don't know the exact statement and its context so I can only guess what was meant: if a script gets sourced instead of executed in a separate shell then any variables or functions defined in this script or any changes to variables will be visible in your shell after the script was done. This might be intended in some cases (and that's why you can source a script) but it might also be an unintended pollution of the current environment of your shell with unwanted side effects.

Thus, unless you explicitly want to let the script make changes to your local bash environment you should execute it as shell-script (i.e. separate shell) and not source it.

And note that this is actually not a problem of information security: from a security standpoint the sourced script and the script executed in a separate shell can both execute malicious code with the permissions of the user.


Source-ing the script pollutes/alters your current environment. It could have future session effects down the line. For a simple example, imagine the following scenario.

I (the attacker) provide some useful script that does something you want. But in addition, my script drops an executable called "sudo" in a hidden directory somewhere. This executable harvests, and sends home to me, its arguments, and calls the system "sudo" command. My script also adjusts the $PATH variable putting my hidden directory first.

If you run my script in its own shell, you get the useful effect you thought you were getting, and my hidden wrapper dropped, but nothing else.

If you sourced my script into your current environment, the next time you type "sudo foo" you will call my hostile wrapper script, which will call the real sudo on your behalf, but I get your info. Maybe days or weeks later.

This is a contrived example, but the point is, source-ing changes you environment after the job is done. Executing in it's own shell limits changes to the work the script does.

Side effects can be abused by attackers.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .