简体   繁体   中英

Difference in invoking shell script from within another shell script

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM