Search code examples
arraysbashyq

How can I use yq with a variable for array index when traversing a YAML file in bash?


Given the yaml file test.yaml:

- alpha
- bravo
  - one
  - two
- charlie
- delta

How do I find the ith element in the array? For example:

i=2

Then array[$i] should return charlie.

I am using Mike Farah's yq.

If I try

yq '.[$i]' test.yaml

I get not the ith element in the array as expected, but rather the entire array! Output:

alpha
bravo - one - two
charlie
delta

What am I doing incorrectly?


Solution

  • Following the yq documentation for environment variable operators, we can use the variable $i like this:

    i=$i yq '.[env(i)]' test.yaml
    # alpha