widget
widget

Reputation: 421

Resolving env inside another env

So i would like to print my env variable which contains other variables. For example i have:

MY_VARS="My var are:\nVAR1 = ${MY_VAR1}\nVAR2 = ${MY_VAR2}"
MY_VAR1=var1
MY_VAR2=var2

and i would like to make it possible in way like:

printf "${MY_VARS}" > my.conf

or

printf "$(echo ${MY_VARS})" > my.conf

to get sth like in my.conf file:

My var are:
VAR1 = var1
VAR2 = var2

but it dosent work. Is ther possibility to do such thing ? I need it to us it with Kubernetes so i can set env in my ReplicationController and use it with Kubernetes envs like SERVICE_HOST and SERVICE_PORT There is another problem that Kubernetes is changing my MY_VARS variable to multiline inside container so it looks like:

MY_VARS=My var are:
VAR1 = ${MY_VAR1}
VAR2 = ${MY_VAR2}

Hope it's quite clear :)

My solution:

while read -r line
do
  printf "$line\n" >> conf.tmp
done <<< "$CONFIG"

while read -r line
do
  eval echo $line >> conf
done < conf.tmp

Where CONFIG variable is passed by me to the container and this variable contains Kubernetes service variables with IPs and Ports. I had to make it twice because eval couldnt resolve \n.

Upvotes: 0

Views: 68

Answers (2)

Antoine Cotten
Antoine Cotten

Reputation: 2762

With bash you can perform indirect references but it would not replace the value of your variable directly, only when you use it from a bash terminal.

Upvotes: 1

pabl0rg
pabl0rg

Reputation: 171

You've got to define the vars first. The following script prints out what you want:

MY_VAR1=var1
MY_VAR2=var2
MY_VARS="My var are:\nVAR1 = ${MY_VAR1}\nVAR2 = ${MY_VAR2}"
printf "${MY_VARS}"

Upvotes: 0

Related Questions