Reputation: 111
I have a yaml file like follows,
dev:
host_place: "some place"
qa:
host_place: "another place"
In a shell script I am trying to get that value. If I hard corded dev or qa those values are showing. But if I get it as a input parameter it does not showing anything. My shell script like below
#! /bin/bash
. yaml_par.sh
eval $(yaml_par config.yml "con_")
host=$con_dev_host_place
echo $host
If I run this it will work without any issue
but if I do below modification it won't work.
#! /bin/bash
. yaml_par.sh
envo=$1
eval $(yaml_par config.yml "con_")
host=$con_$envo_host_place
echo $host
What could be the reason?
Upvotes: 0
Views: 1298
Reputation: 2662
For bash:
If a value in variable is used in an another variable name use eval
to get the value:
eval host=\$con_${envo}_host_place
Upvotes: 0
Reputation: 80921
Your second example doesn't expand the way you think it does.
Think about it. You are expecting the shell to look at $con_$envo_host_place
and realize that you meant for it to expand $envo
first to get $con_dev_host_place
and then expand that to get the value.
How is the shell supposed to know that?
You might think you can do ${con_${envo}_host_place}
to force the issue but that doesn't work either. You just get a "bad substitution" error from the shell.
You can have indirect shell variable expansion however. This is covered in Bash FAQ 006.
# Bash realvariable=contents ref=realvariable echo "${!ref}" # prints the contents of the real variable # ksh93 / mksh / Bash 4.3 realvariable=contents typeset -n ref=realvariable echo "${!ref} = $ref" # prints the name and contents of the real variable # zsh realvariable=contents ref=realvariable echo ${(P)ref} # prints the contents of the real variable
Upvotes: 1