To source and export variables from a file in Bash, you need to use the source command (or its shorthand, the dot .) when executing the file. This runs the script in the current shell, making its variables available to subsequent commands and processes. 

Method 1: Include export in the file 

The most common and straightforward method is to include the export keyword before each variable definition within the file itself. 

File: environment_variables.sh 

export DB_HOST="localhost"
export DB_USER="myuser"
export API_KEY="your_api_key_here"
# Variables defined with 'export' are passed to child processes

To use it:
In your current shell or another script, use the source command or the . operator to load these variables: 

source environment_variables.sh
# or the portable POSIX alternative:
. environment_variables.sh

After running this, you can access the variables:

echo $DB_HOST
# Output: localhost

Method 2: Automatically export all variables from a file 

If you have a file with many key-value pairs but no export keywords, you can use the set -a (or set -o allexport) option to automatically export all variables defined after that point in the current shell session. 

File: config.env 

VAR1="value1"
VAR2="value2"
VAR3="value3"

To use it:

# Enable automatic exporting
set -a
# Source the file
source config.env
# Disable automatic exporting (optional, but good practice)
set +a

Now the variables are exported in your current shell: 

echo $VAR2
# Output: value2

Leave a Reply