Reputation: 6685
I have two shell scripts a.sh
and b.sh
in my home directory. Within a.sh i invoke b.sh as
sh b.sh
I can also do it the following way
. b.sh
Kindly tell me the differences between the invocations.
Thanks, LinuxPenseur
Upvotes: 1
Views: 620
Reputation: 6891
The second way is called "sourcing", it pulls the script in and executes it in the same shell.
You would do this for two reasons: Speed, and so the second script can set environment variables in your first script. Normally when running a script or program, it can't change the caller's environment.
Sourcing is faster because it doesn't require forking and starting another shell process. You see this used in things like /etc/init/rc scripts on some systems, but the performance difference is probably not important for most uses. There are also some subtleties to do with signal handling when sourcing scripts.
Upvotes: 1
Reputation: 46985
The first way:
sh b.sh
creates a subshell and runs b.sh within the subshell. One of the consequences of doing it this way is that any environment variables set in b.sh will simply vanish when you return to a.sh
The second method:
. ./b.sh
sources b.sh and therefore any env vars set in b.sh will remain visible to a.sh when b.sh returns.
Upvotes: 5