Skip to main content

Bash - Loading environment variables from a file

ยท 2 min read

Bash - Loading environment variables from a file

Imagine you've a .env file like and you wish to process that file in a Bash script.

DOCKER_GIT_FULLNAME="Christophe Avonture"

Using a configuration file will enable you to externalize the management of your constants, as well as reuse variables from another application, such as a site developed in Laravel.

Let's take a look at how to do this as correctly as possible.

The snippet comes from

You can load that file easily in your environment using the following instructions:

set -o allexport
source .env set
set +o allexport

This done, variables will be accessible like any environment variables in your bash script. When the script exit, the added variables are removed (just like in a sub-shell).

Using source is the best solution to avoid problems with f.i. spaces like in Me and myself i.e. using other solutions like export $(... | xargs) will always give unpredictable results.

To illustrate this, simply create a file called f.i. with this content:

#!/usr/bin/env bash

set -o allexport
source .env set
set +o allexport


Using the .env file provided here above, we'll obtain this output:

โฏ ./

Christophe Avonture (

This is, I think, the best and, too, the easiest way to use an external file to store configuration items in Bash.