What does the 'source' command do?

Question

What does the source command do?

Answer

Source evaluates any file written after, the file if containing any commands to run, it will execute them in the order they were written in the file. for example if our file had:

echo 'This is the first one'
echo 'second'
echo 'and third'

when running: source <ourFilename> or . <ourFilename> (because . is the shorthand for the source command) we will see:

This is the first one
second
and third

of course, it does not only work with the echo command, but with any kind.

Something to keep in mind is that source's . version is not the same as ./, dot space and file name is the source command running the commands in the written file, but with ./ dot is simply a mark of origin, stating that the origin from which the path will be read is the current directory. Like: ./someDir/somefile means that someDir/ is in the same location that we presently are.

20 Likes

source command runs the script in the current shell only. If you do not use source, then it spawns a shell as a child process and executes commands in that.

For example-
If you want to set a proxy environment variable in terminal and you have written the command for that in a script named “export_connect.sh”

Now, if you use-
source export_connect.sh or . export_connect.sh - then the environment variable of the current shell will be set

If you use ./export_connect.sh , then the environment variable will not be set in your current terminal, as it opens a new shell and sets the environment variable in it and then closes it.

6 Likes