Home > database >  How to read each line in .tfvars and export key value as environmental var in bash?
How to read each line in .tfvars and export key value as environmental var in bash?

Time:01-12

I want to read from .tfvars which is variables_file_2 and export each variable (key) and value of it as environmental variable in bash so I can access it in my script

grep "^[^#]" "${variables_file_2}" > manifest.tfvars

while read line;
do
    export "$(echo "${line}" | tr -d "\"")"
done < manifest.tfvars

Currently getting

export: `{={': not a valid identifier

as error.

sample of .tfvars is

region = "us-east-2"

CodePudding user response:

You might want to use something more robust:

LANG=C awk -v OFS='=' '
    $1 ~ /^[[:alpha:]_][[:alnum:]_]*$/ && $2 == "=" && match($0,/".*"/) {
        print $1, substr($0,RSTART 1,RLENGTH-2)
    }
' "${variables_file_2}" > manifest.tfvars

while IFS='=' read -r var value
do
    export "$var"="$value"
done < manifest.tfvars

note: the awk assumes that the = are always surrounded by at least a space character

CodePudding user response:

The code

grep "^[^#]" "${variables_file_2}" > manifest.tfvars

Looks like you're trying to remove/delete lines starting with a #

and the tr seems like trying to delete the quotes around the assignment after the = sign.

Something like this might do it.

#!/usr/bin/env bash

while IFS= read -r line; do
  echo export -- "$line"
done < <(sed '/^#/d;s/ = /=/;s/"//g' "${variables_file_2}")

With the assumption that the input from "${variables_file_2}" is something like.

#
region = "us-east-2"
#

With

sed '/^#/d;s/ = /=/;s/"//g' "${variables_file_2}"

Or even like

sed '/^#/d;s/^\([^ ]*\) = "\([^"].*\)"/\1=\2/' "${variables_file_2}"

The output should be.

region=us-east-2
  • Remove the echo if you're ok with the output.
  • Related