Reputation: 249
data.yml
variables:
count: "100"
name: "sss"
pass: "123"
file.sh
#!/bin/bash
echo "Details are "$name":"$pass" - Total value "$count"
I need to fetch the variable values from data.yml and pass to file.sh
calling file.sh should give Output:
Details are sss:123 - Total value 100
Upvotes: 4
Views: 4270
Reputation: 10304
Read name value pairs from yq
and use bash printf -v
to initialize variables.
A little over the top, but a nice way to initialize a script.
Note that adding variables does not change the while loop.
file.sh
#!/bin/bash
while read -r key val; do
printf -v "$key" "$val"
done < <(yq '.variables[] | key + " " + .' data.yml)
echo "Details are $name: $pass - Total value $count"
echo 'Some extra variables:'
echo "\$address: $address, \$phone: $phone, \$url: $url"
data.yml
variables:
count: "100"
name: "sss"
pass: "123"
address: "42 Terrapin Station"
phone: "999-999-9999"
url: "http://www.example.com"
output
Details are sss: 123 - Total value 100 Some extra variables: $address: 42 Terrapin Station, $phone: 999-999-9999, $url: http://www.example.com
Upvotes: 4
Reputation: 335
There is a cli tool yq
to parse yaml files.
The script would look like this:
#!/usr/bin/env bash
name=$(yq '.variables.name' data.yaml)
pass=$(yq '.variables.pass' data.yaml)
count=$(yq '.variables.count' data.yaml)
echo "Details are $name: $pass - Total value $count"
Of course you can also pass the file as argument.
Upvotes: 3
Reputation: 26437
You can use a single call to yq
and put values in an array :
#!/usr/bin/env bash
mapfile -t array < <(yq '.variables[]' data.yml)
declare -p array
Upvotes: 2