How to interpolate strings that represent environment variables

2.8k views Asked by At

I've got this runtime need to replace environment variables in a plain text file. Say the file looks like this:

version: v1
kind: Pod
metadata:
  - name: $PODNAME

My bash script pulls out all environment vars, here $PODNAME.

Once I have a handle on what string tokens are environment variables, I'd like to replace them with the environment var value from the host running the script. So above, I'd replace the string $PODNAME with the env value of $PODNAME.

With what I have, I can list all env vars. But I can't seem to get the replacement done. For my toy example, I'd like to echo out both the string token and the value it should replace:

    #!/bin/bash
    IFS=', ' read -a array <<< $(grep -F -- "$" file.yaml | sed -e 's/          value: //' | tr '\n' ' ')
    for element in "${array[@]}"
    do
        echo "$element"
    done

I've tried stuff like this:

        echo "$element ${$element}"

I've done some searches but can't seem to find the StackOverflow question that already covers this weird usecase.

3

There are 3 answers

0
buley On BEST ANSWER

Heredoc would have been a good approach, but doesn't jibe with what I was attempting to do:

I'd like to echo out both the string token and the value it should replace

I was on the right track with this:

echo "$element ${$element}"

In the end, here's what worked:

EL=$(echo "$element" | sed 's/\$//')
echo "$element ${!EL}"

Upvotes for all, regardless.

0
Cyrus On

Use a here document:

PODNAME="foo"

cat << EOF
version: v1
kind: Pod
metadata:
  - name: $PODNAME
EOF

Output:

version: v1
kind: Pod
metadata:
  - name: foo
0
Nathan Wilson On

If you have gnu sed, it can be done with the e action of sed.

$ export PODNAME=foo

$ cat file.yaml 
version: v1
kind: Pod
metadata:
  - name: $PODNAME

$ sed -r 's/^(.*) (\$[A-Z]+)/echo "\1 \2"/e' file.yaml
version: v1
kind: Pod
metadata:
  - name: foo

The environment variable needs to be exported for sed to see it's value.