'Fetch variables values from yml and pass to shell script?

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


Solution 1:[1]

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 -r '.variables | keys[] as $k | "\($k) \(.[$k])"' 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.examle.com"

output

Details are sss: 123 - Total value 100
Some extra variables:
$address: 42 Terrapin Station, $phone: 999-999-9999, $url: http://www.examle.com

Solution 2:[2]

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

Solution 3:[3]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Philippe
Solution 3