Home > Enterprise >  How to read a specific data from a yaml file inside a shell script
How to read a specific data from a yaml file inside a shell script

Time:04-20

I have a yaml file say "test.yaml". The below is the content of yaml file.

...
test:
  config:
    abc: name1
    xyz: name2
...

Now I want to read the value of abc and xyz alone from the yaml inside a shell script and store it in two variables inside shell script. test.yaml file contains additional data apart from the above one which I don't need to bother about that inside this shell script.

Eg: test.sh

var1=name1 //test[config[abc]]
var2=name2 //test[config[xyz]]

How do I read specific data (as key-value) from yaml inside a shell script. It would be really helpful if someone helps me out on this. Thanks in advance!!!

CodePudding user response:

Here's an example with . All of the following assumes that the values do not contain newlines.

Given

$ cat test.yaml
---
test:
  config:
    abc: name1
    xyz: name2

then

yq e '.test.config | to_entries | map(.value) | .[]' test.yaml

outputs

name1
name2

You can read them into variables like

{ read -r var1; read -r var2; } < <(yq e '.test.config | to_entries | map(.value) | .[]' test.yaml)
declare -p var1 var2
declare -- var1="name1"
declare -- var2="name2"

I would read them into an associative array with the yaml key though:

declare -A conf
while IFS="=" read -r key value; do conf["$key"]=$value; done < <(
    yq e '.test.config | to_entries | map([.key, .value] | join("=")) | .[]' test.yaml
)
declare -p conf
declare -A conf=([abc]="name1" [xyz]="name2" )

Then you can write

echo "test config for abc is ${conf[abc]}"
# or
for var in "${!conf[@]}"; do printf "key %s, value %s\n" "$var" "${conf[$var]}"; done
  • Related