In Bash scripting, the source
command is a built-in function that allows you to execute commands from a file in the current shell environment. Unlike running a script normally, which spawns a new subshell, source
executes the script in the current shell, making it a crucial tool for managing environment variables, functions, and other settings.
source
Command
The source
command, sometimes represented by a dot (.
), reads and executes the contents of a file as if the commands were typed directly into the current shell session.
1. Basic Usage of source
:
source /path/to/script.sh
script.sh
in the current shell environment.
2. Alternative Syntax Using the Dot (.
):
. /path/to/script.sh
.
) is a shorthand for source
and functions identically.
source
The source
command is particularly useful when you want the effects of a script to persist in the current shell session, such as setting environment variables or defining functions.
3. Loading Environment Variables:
Suppose you have a script, set_env.sh
, that defines several environment variables:
export VAR1="value1"
export VAR2="value2"
source set_env.sh
will load VAR1
and VAR2
into the current shell session, making them available for subsequent commands.
4. Defining Functions for the Current Session:
You can define functions in a script and load them into the current session with source
:
my_function() {
echo "This is a function"
}
source my_script.sh
, my_function
will be available for use in the current session.
When you execute a script normally (e.g., bash script.sh
), it runs in a subshell. Any changes made to the environment (like setting variables) do not affect the parent shell. source
avoids this by running the script directly in the current shell.
5. Example of Running in a Subshell:
# script.sh
export VAR="value"
bash script.sh
will set VAR
in the subshell, but VAR
will not be available in the parent shell.
source script.sh
ensures VAR
is set in the current shell.
source
6. Loading Shell Configuration Files:
The source
command is often used to load or reload shell configuration files, such as .bashrc
or .bash_profile
.
source ~/.bashrc
.bashrc
file, applying any new configurations without requiring you to start a new session.
7. Sourcing Scripts to Modify the Current Environment:
# environment_setup.sh
export PATH="$PATH:/new/path"
alias ll="ls -la"
source environment_setup.sh
, the PATH
variable is updated, and the ll
alias is set in the current session.
source
source
only when necessary, as it can alter the current environment in ways that might be unintended.
By understanding the source
command, you can effectively manage your Bash environment, load configurations dynamically, and make your scripts more powerful and flexible.
Jorge García
Fullstack developer