What Is the Difference Between Executing a Bash Script vs Sourcing It?

What Is the Difference Between Executing a Bash Script vs Sourcing It?

What is the difference between executing a Bash script like A and sourcing a Bash script like B?

A
> ./myscript

B
> source myscript
2

7 Answers

Both sourcing and executing the script will run the commands in the script line by line, as if you typed those commands by hand line by line.

The differences are:

  • When you execute the script you are opening a new shell, type the commands in the new shell, copy the output back to your current shell, then close the new shell. Any changes to environment will take effect only in the new shell and will be lost once the new shell is closed.
  • When you source the script you are typing the commands in your current shell. Any changes to the environment will take effect and stay in your current shell.

the "environment" are things like the current working directory and environment variables. also shell settings (among others history and completion features). there are more but those are the most visible.

Use source if you want the script to change the environment in your currently running shell. use execute otherwise.

If you want more details please read on.

Terminology

To clarify some common confusion about the syntax to execute and the syntax to source.

Syntax to execute:

./myscript

This will execute myscript provided that the file is executable and located in the current directory. The leading dot and slash (./) denotes the current directory. This is necessary because the current directory is usually not (and usually should not be) in $PATH.

myscript

This will execute myscript if the file is executable and located in some directory in $PATH.

Syntax to source:

source myscript

This will source myscript. The file need not be executable but it must be a valid shell script. The file can be in current directory or in a directory in $PATH.

. myscript

This will also source myscript. This "spelling" is the official one as defined by POSIX. Bash defined source as an alias to the dot.

and for completeness:

exec myscript

This will terminate the current shell and then execute myscript in place of the terminated shell. That means when myscript is done there no shell to return to. exec is powerful but rarely needed.

I put some links at the end for more information on these topics.

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.