1

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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.