source (Execute Shell Script and Refresh Environmental Variables)
The source
command is used to execute shell scripts and refresh environmental variables.
Running shell script with the source command
If you run a shell script with an absolute address like what we demonstrated in the previous section, variables are not properly registered in the OS. When you run the same shell script with the source
command, you can use the variable set of that shell script for another process.
For example, you can run the shell script with the absolute path only.
./variable_parent.sh
A shell variable in the parent shell script
abc=2023
An environmental variable in the parent shell script
ABC=1988
A shell variable in the child script
abc=
An environmental variable in the child script
ABC=1988
Then, try to call $ABC in the command line, but there will be no response from the shell.
echo $ABC
Next, run the same script with the source
command. The command line displays the same results as the one run without the source
command.
source variable_parent.sh
A shell variable in the parent shell script
abc=2023
An environmental variable in the parent shell script
ABC=1988
A shell variable in the child script
abc=
An environmental variable in the child script
ABC=1988
However, when you call $ABC in the command line, you'll get an assigned value.
echo $ABC
1988
This is because the source
command properly registered ABC in the environmental variable.
Tips: env command
You can check the environmental variable in the system by running the env
command.
When you run the env
command, you'll see multiple preset environmental variables as shown below.
env
SHELL=/bin/bash
PWD=/home/ubuntu
LOGNAME=ubuntu
XDG_SESSION_TYPE=tty
MOTD_SHOWN=pam
HOME=/home/ubuntu
:
You can use the grep
command to find a specific environmental variable. For example, if you want to check that ABC is registered as an environmental variable, run the following command.
env | grep ABC=
ABC=1988