Ubuntu – Using source vs bash commands



mkdir test
echo $1
echo $2

It appears that following two commands do the same things. Are they the same? If not, how could I alter my example to show the difference?

cat test.sh | bash -s hi bye
source test.sh hi bye

Best Answer

The difference will be if you are trying to alter the environment of your current shell (i.e. set a shell or environment variable). For example

$ cat test.sh
$ unset myVariable; source test.sh; echo ${myVariable:-null}
$ unset myVariable; bash -s < test.sh; echo ${myVariable:-null}

This is what source is for: evaluate a script in the current shell. When you launch a new bash process, it cannot alter the parent process's environment.