Setting environment variables based on key-value pairs in a file, where some values are quoted expressions

bash, environment-variables

Solution

First -- if you trust your file to be safely evaluated as a shell script with your current user's privileges, this could be as simple as:

set -a                           # automatically export all shell variables
source "${SOURCE}/../params.env" # evaluate file as a shell script
set +a                           # turn off automatic export

Otherwise, the answer by mklement0 is appropriate.

Problem

I have made the following bash script in order to export values from a specific file named `params.env`: ``` #!/bin/bash SOURCE="${BASH_SOURCE[0]}" while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" SOURCE="$(readlink "$SOURCE")" [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located done SOURCE=$(dirname ${SOURCE}) export $(cat "${SOURCE}/../params.env" | xargs) ``` The `params.env` has the values: ``` Param1=param1 Param2="Space separated value" ``` But it successfully exports Param1 but it fails to export Param2. Do you have any idea how to solve this?

Original source