What happens when you run bash foo.sh
?
A fresh bash process starts and reads and executes the commands that are in foo.sh
. When it's done executing the commands, this new process exits and you get your prompt back, echoed by your current shell.
What happens when you run source foo.sh
(or . foo.sh
) ?
You basically tell your current shell "instead of reading commands from the keyboard, read commands from this file, when you're done, come back to the keyboard"
When does it matter ?
When there are commands that change the state of the shell; for example cd
, exit
, VAR=value
, alias
and a few other.
Suppose foo.sh
contains this :
mkdir /tmp/bar
It does not matter if you run it with source
or bash
.
Now, suppose the content of the script changes variables, then it matters. When you run bash foo.sh
, a new bash is created, it runs the commands and exits; no change in your shell. If, on the other side, you source foo.sh
, your current shell variables are changed.
Let's take an example. Suppose there is this in file foo.sh
:
echo "Currently executing commands from foo.sh"
echo "changing variable foo."
foo=$RANDOM
echo "In shell with PID $$, the value of foo is now >>$foo<<"
echo "End of foo.sh"; echo
What happens if you run bash foo.sh
and then echo $foo
?
What happens if you run source foo.sh
and then echo $foo
?
Try multiple times. You'll notice that if you run bash foo.sh
, the foo variable is not set in your shell. if you run source foo.sh
, the foo variable is set (and changed) each time.