Ubuntu – Using source vs bash commands

bash

test.sh

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
myVariable=foo
$ unset myVariable; source test.sh; echo ${myVariable:-null}
foo
$ unset myVariable; bash -s < test.sh; echo ${myVariable:-null}
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.