0

How to use dynamic variables in expression

myres.txt

[
{
"name": "test-001",
"is_preconfigured": true,
},
{
"name": "my-connector",
"is_preconfigured": 3
},
{
"name": "checkerfrom_default2_002",
"is_preconfigured": false,
}
]

When i use direct command yq e '. | .[].name | select(. == "my-connector")' myres.txt This gives me result as my-connector

But when I use following way NAME_IN_YAML="my-connector"

EXISTING_NAME=$(yq e '. | .[].name | select(. == $NAME_IN_YAML)' myres.txt)

This is blank result

enter image description here

1 Answers1

4

With mikefarah/yq use the env(..) function to load environment variables from the shell, i.e.

NAME_IN_YAML="my-connector" yq e '.[].name | select(. == env(NAME_IN_YAML))' myres.txt

Note that, if you are using yq version above 4.18.1, the eval action e is the default one and can be skipped altogether.


If you are looking to format/manipulate JSON text, you should probably consider using jq which has loads of features to use.

Inian
  • 80,270
  • 14
  • 142
  • 161
  • 1
    @DnyaneshwarJadhav: You didn't run the command as I told in the answer. `NAME_IN_YAML="my-connector"` has to be set in the same line as the `yq` command and not before. See [Passing environment variables to a process](https://stackoverflow.com/q/41183403/5291015) – Inian Jun 24 '22 at 10:11
  • Hey I got your point now, I was doing it in two different lines, this was causing my problem. I am able to get the results, thanks for your help and patience to understand deeply. :) – Dnyaneshwar Jadhav Jun 24 '22 at 11:54