Introduction
Source is a command to read a file then execute its contents. It helps to load variables, functions, and configuration files into shell scripts.
Source is a shell built-in command and some shells in Linux and UNIX. It passed as an argument in the current shell script.
This article will show you how to use the source command in Linux as we go through below.
The syntax of source command
$ source FILENAME [ARGUMENTS]
We can replace source command by the .(dot)
$ . FILENAME [ARGUMENTS]
How to use source command
1. Refresh current shell environment
When using Linux, a user can define alias in the current shell environment. For example, to display hidden files, we use ls -la. But we can use faster way by alias:
$ alias la=‘ls -la’
Then we only type la to display hidden file:
But this is only temporary, for permanent use, open the .bashrc file and type:
alias la= ‘ls -la’
Refresh the current shell environment, type:
$ source ~/.bashrc
2. Execute shell script in the current shell environment
A shell script can’t understand the variables you define in the current shell environment. So we must use the source command.
For example, we will try to run apt command
Firstly, let’s create file update.sh and start with:
#!bin/bash
Secondly, type the following command:
sudo apt update
Lastly, save and execute it by source command:
$ source ./update.sh
Output:
3. Import a shell function
For example:
Firstly, let’s create file foo.sh and start with:
#!bin/bash
Secondly, define a custom shell script. Here I put a function named foo:
foo () { echo “Hello” }
Let’s save it.
To import the foo function, run the following command:
$ source foo.sh
To run the shell function, type:
$ foo
Output:
4. Read and execute commands
Let’s say you want to execute 2 commands ls and df -h, let’s create a file *txt contains those 2 commands. Here I will create file example.txt:
And save it. Then run source filename:
$ source example.txt
Output:
Conclusion
You’ve already gone through the details of how to use the source command in Linux.
Thanks for reading.