Home > other >  Unable to find match with yq in for loop
Unable to find match with yq in for loop

Time:04-18

I have a yaml file called teams.yml that looks like this:

test:
  bonjour: hello
loop:
  bonjour: allo

I want to loop over an array and get itsvalues matching a key in the yaml. I have tried yq e 'keys | .[] | select(. == "test")' .github/teams.yml and it returns test whereas yq e 'keys | .[] | select(. == "abc")' .github/teams.yml returns nothing which is enough to get the information I am interested in.

The issue is that, when using the same logic in a for loop, yq returns nothing:

#!/bin/bash

yq e 'keys | .[] | select(. == "abc")' .github/teams.yml # Prints nothing
yq e 'keys | .[] | select(. == "test")' .github/teams.yml # Prints 'test'

ar=( "abc" "test" "xyz" )
for i in "${ar[@]}" # Prints nothing
do
  yq e 'keys | .[] | select(. == "$i")' .github/teams.yml 
done

What explains the lack of output in the for loop?

CodePudding user response:

Call yq with the loop variable set in the environment, and use env within yq to read environment variables. See also the section Env Variable Operators in the manual.

ar=( "abc" "test" "xyz" )
for i in "${ar[@]}" # Prints nothing
do
  i="$i" yq e 'keys | .[] | select(. == env(i))' .github/teams.yml 
done

Another way could be to import the (preformatted) array from the environment and just make the array subtractions within yq (saving you the looping and calling yq multiple times):

ar='["abc","test","xyz"]' yq e 'env(ar) - (env(ar) - keys) | .[]' .github/teams.yml 
  • Related