Last Updated: September 27, 2021
·
4.42K
· destructuring

Reading YAML files in bash with ruby

If you have ruby, here's a function that lets you read in a YAML file and extract a hash, list, or a scalar value:

function ryaml {
  ruby -ryaml -e 'puts ARGV[1..-1].inject(YAML.load(File.read(ARGV[0]))) {|acc, key| acc[key] }' "$@"
}

Ruby has yaml already in the standard library (but not json!). It's pretty fast, too.

Hashes are returned looking like JSON - working on getting that into YAML so the output of ryaml can be fed into another ryaml, like:

ryaml <(ryaml hosts.yml mikan keys) work

Lists are one value per line. Scalars look like a list of one value. Probably best to avoid returning a hash.