Search code examples
bashyamlyq

Filter null case when reading in keys from YAML with yq


Say I have a yaml file, example.yaml:

test:
services:
  registry:
    image: registry:2
    ports:
      - "5000:5000"
      - "337:337"
  pinger:
    build:

I can read in the services to a bash array like so:

readarray -t services  <<< $(yq e '.services | keys | .[]' example.yaml)

But when I try the case where the key has no sub-keys, I get an error:

yq e '.test | keys | .[]' example.yaml
Error: Cannot get keys of !!null, keys only works for maps and arrays

What is a good way of replacing the null case with a falsey value? Ultimately I'd like test to be stored as a bash variable ( == false).


Solution

  • Use the select() function in combination with the not operator to filter out the null values before applying the keys function like this;

    yq e '.test | select(.) | keys | .[]' example.yaml
    

    The select(.) expression will return all non-null values in the test key. You can use the same approach for those keys as well:

    yq e '.test | select(.) | keys | .[]' example.yaml
    yq e '.services | select(.) | keys | .[]' example.yaml