While we may all be familiar with executing scripts, how does it compare to sourcing scripts? I have sourced scripts before but didn't really bother really digging into the differences. Let's get into it.
Visual representation of the difference
- executing
1
2
3
4
5
6
7# this executes the script in the current directory
# must be executable
$ ./script
# this executes the script if located in some directory in $PATH
# must be executable
$ script - sourcing
1
2
3
4
5
6
7# this sources the script
# does NOT have to be executable
$ source script
# also sources the script and need NOT be executable
# does exactly the same thing as `source script` because bash defines `source` as an alias to the dot
$ . script
Verbal representation of the difference
- Executing
- Runs all the commands in a new/separate shell.
- Any changes to the environment as a result of the commands only apply to the new shell. This means the environment in the current shell remains untouched.
- Sourcing
- Runs all the commands in the current shell.
- Any changes to the environment resulting from the commands will apply in the current shell.
References
What is the difference between executing a Bash script vs sourcing it?