Skip to content
Advertisement

Reading and exporting key-value pairs from a file in bash script (without caching)

I have the following project directory structure:

myproj/
    .env
    setenv.sh
    run.sh

Where run.sh looks like:

#!/bin/sh

sh setenv.sh

echo "$fizz"

Where .env is a properties file of key=value pairs like so:

fizz=buzz
foo=bar
color=red

The setenv.sh script needs to read the key-value pairs out of .env and export/source them, so that run.sh can reference them at runtime and they will evaluate to whatever their values are in .env.

The run.sh script and setenv.sh scripts need to run on Linux and/or Mac (so where uname is 'Linux', 'FreeBSD' or 'Darwin') and I need to be able to run run.sh over and over, each time with different values in .env, and have them take effect on each run.

Currently my setenv.sh looks like:

#!/bin/sh
unamestr=$(uname)
if [ "$unamestr" = 'Linux' ]; then
    export $(grep -v '^#' .env | xargs -d 'n')
elif [ "unamestr" = 'FreeBSD' ] || [ "unamestr" = 'Darwin' ]; then
    export $(grep -v '^#' .env | xargs -0)
fi

When I run sh run.sh it echoes the value buzz. But if I change fizz to another value, say, buzz2, and re-run run.sh, it still ouputs the fizz value as being buzz. What can I do so that the values in .env are always dynamically loaded/exported/sourced/etc. on each run of run.sh?

Advertisement

Answer

The issue is when you run sh setenv.sh it starts a new shell session and runs the script there. So, the new session’s environment is configured, not yours.

As @Philippe suggested, you should “source” setenv.sh:

source setenv.sh # this is one way
. setenv.sh # this is another way

echo "$fizz"

Above code runs the content of setenv.sh in the current session, rather than in another session.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement