yq/pkg/yqlib/doc/operators/eval.md

39 lines
947 B
Markdown
Raw Normal View History

2022-02-01 03:47:51 +00:00
# Eval
Use `eval` to dynamically process an expression - for instance from an environment variable.
`eval` takes a single argument, and evaluates that as a `yq` expression. Any valid expression can be used, be it a path `.a.b.c | select(. == "cat")`, or an update `.a.b.c = "gogo"`.
2022-02-01 03:47:51 +00:00
Tip: This can be a useful way to parameterise complex scripts.
2022-02-01 03:47:51 +00:00
## Dynamically evaluate a path
Given a sample.yml file of:
```yaml
2023-05-05 04:13:18 +00:00
{pathExp: '.a.b[] | select(.name == "cat")', a: {b: [{name: dog}, {name: cat}]}}
2022-02-01 03:47:51 +00:00
```
then
```bash
yq 'eval(.pathExp)' sample.yml
```
will output
```yaml
2023-05-05 04:13:18 +00:00
{name: cat}
2022-02-01 03:47:51 +00:00
```
## Dynamically update a path from an environment variable
The env variable can be any valid yq expression.
Given a sample.yml file of:
```yaml
2023-05-05 04:13:18 +00:00
{a: {b: [{name: dog}, {name: cat}]}}
2022-02-01 03:47:51 +00:00
```
then
```bash
pathEnv=".a.b[0].name" valueEnv="moo" yq 'eval(strenv(pathEnv)) = strenv(valueEnv)' sample.yml
2022-02-01 03:47:51 +00:00
```
will output
```yaml
2023-05-05 04:13:18 +00:00
{a: {b: [{name: moo}, {name: cat}]}}
2022-02-01 03:47:51 +00:00
```