hoylemd
hoylemd

Reputation: 456

Set an environment variable defined by a string?

I'm writing a script to copy config variables from a cloud storage service into environment variables (for local development only, to avoid making a whole bunch of requests whenever an app or test server starts up). I already have a file that is a line-separated list of the variable names.

I know how to set an environment variable with a known name:

export SOME_VAR=some_value

What I don't know is how to set an environment variable with an "unknown" (at write-time) name. So I'd read in that file of variable names, and loop over the list, requesting and exporting each variable.

So the main question is: How do I programmatically set an environment variable whose name exists only in a string at run-time?

Upvotes: 0

Views: 4129

Answers (2)

Saboteur
Saboteur

Reputation: 1428

Your script actually should not work with cat|while, because in this case, while will be executed in child process and any set or export will affect only child process. After end of loop, all variables will be lost.

Try this one:

#! /usr/bin/env bash
while IFS= read -r line; do
  export $(echo ${line^^})=$(get_value_from_secret_store "$line")
done < list_of_vars_file.txt

Upvotes: 1

hoylemd
hoylemd

Reputation: 456

I figured it out!

If you have the value you want in $value, and the name of the env var you want to set in $name, you can do this:

export "$name"="$value"

Bonus tip:

I also needed to upcase the variable names, which can be done with:

up_name="$(echo "$name" | tr '[:lower:]' '[:upper:]'"

So my final script ended up being:

#! /usr/bin/env bash

cat < list_of_vars_file.txt | while IFS= read -r line; do
  value="$(get_value_from_secret_store "$line")"
  up_name="$(echo "$line" | tr '[:lower:]' '[:upper:]')"

  export "$up_name"="$value"
done
``

So the env vars can be copied from the secret store (e.g. vault) to the current shell's environment by sourcing that script (After the correct secret retrieval command is swapped in, of course)

Upvotes: 1

Related Questions