Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
The source command can be used to read a file and treat its content as a set of commands to execute.
In this quick tutorial, we’ll explore how the Linux source command can help us in such situations to execute commands and refresh the environment variables.
Let’s look at the basic syntax:
$ source FILENAME [arguments]
$ . FILENAME [arguments]
As we can see above, the dot or period character ‘. ‘ is a synonym for the source keyword. As such, there is no difference in output between the two.
To see the source command in action, let’s use it:
$ cat test.txt
printf "Today's date is: "
date
echo
cal -3
$ source test.txt
Today's date is: Sat May 23 07:26:50 IST 2020
2020
April May June
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 1 2 1 2 3 4 5 6
5 6 7 8 9 10 11 3 4 5 6 7 8 9 7 8 9 10 11 12 13
12 13 14 15 16 17 18 10 11 12 13 14 15 16 14 15 16 17 18 19 20
19 20 21 22 23 24 25 17 18 19 20 21 22 23 21 22 23 24 25 26 27
26 27 28 29 30 24 25 26 27 28 29 30 28 29 30
31
Here, we first created the file text.txt, which contains the commands to display the date and calendar on the console. After that, we ran the source command and passed our file name as an argument.
Finally, we were able to execute all these commands and see the output on the console.
When we run a script using the source command, all the commands are executed in the same shell. As a result, any variable that has been assigned a value in the script will retain its value after the execution is complete.
This is the main reason it’s popularly used to source environment variables into the current terminal session.
Sometimes, there’s confusion between the source and the bash commands because both can execute commands in a script. The key difference here is that the source command creates variables in the same shell, while the bash command creates a new shell and then executes all the script commands inside it.
Therefore, we can’t use the bash command to set the environment variables, as those variables are destroyed once the bash shell exits.
In this quick tutorial, we’ve seen how to use the source command and how it differs from the bash command.