Environment Variables – Expand Environment Variable from JSON File

environment-variablesjq

I have a JSON file which contains the following (amongst other properties):

{
  "environment": "$USER"
}

I am extracting that value using jq like so:

ENVIRONMENT="$(jq -r '.environment' "properties.json")"

I want the value of ENVIRONMENT to be my username, not the string $USER – is this possible?

Best Answer

Option 1: Just read variable by name

bash allows having variables that reference variables, example:

REF='USER'  # or get it from JSON
echo "${!REF}"
# prints current username

So you can write this:

ENVIRONMENT_REF="$(jq -r '.environment' "properties.json")"
ENVIRONMENT="${!ENVIRONMENT_REF}"

JSON contents:

"environment": "USER"

Option 2: Full shell expansion

Other option, maybe better (but definitely NOT secure) is using eval:

ENVIRONMENT="$(eval "echo $(jq -r '.environment' "properties.json")")"

Note that this is not secure and malicious code can be inserted to the JSON file. What malicious code? Let's look into this properties.json file:

{
    "environment": "$(rm some_file)" 
}

The shell will evaluate this code:

echo $(rm some_file)

… and the file named some_file will be deleted. As you can see, depending on the command entered there, you can cause very serious damage.

Related Question