Differences between executing a file “./script.sh” and sourcing a file “source script.sh”

Example Script:

$cat setEnv.sh

#export java home to current shell environment

export JAVA_HOME=$(/usr/libexec/java_home)

Executing a file “./script.sh”:

Linux take script.sh as a executable binary file.

When the file is executed, a new sub-shell will be created and the script is run in the new sub-shell. When it finishes, the sub-shell exit automatically. So executing this file does not make any changes of the current shell.

$ ./setEnv.sh

$ echo $JAVA_HOME

So in this case, JAVA_HOME is still not set in current shell.

Sourcing a file “source ./script.sh” “. ./script.sh”

Sourcing will run the commands in the current shell process. The lines of code were executed as if they were printed at the command line. So it is import to source a file to make the changes of the file applicable to current shell. Usually, the alias or profile files are often sourced since they contain stuffs like setting of environment variables , aliases definition, etc.

bash-3.2$ source setEnv.sh

bash-3.2$ echo $JAVA_HOME

/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s