yq/operators/boolean-operators.md
2022-03-29 11:12:22 +11:00

3.5 KiB

Boolean Operators

The or and and operators take two parameters and return a boolean result.

not flips a boolean from true to false, or vice versa.

any will return true if there are any true values in a array sequence, and all will return true if all elements in an array are true.

any_c(condition) and all_c(condition) are like any and all but they take a condition expression that is used against each element to determine if it's true. Note: in jq you can simply pass a condition to any or all and it simply works - yq isn't that clever..yet

These are most commonly used with the select operator to filter particular nodes.

  • equals / not equals (==, !=) operators here
  • comparison (>=, < etc) operators here
  • select operator here

{% hint style="warning" %} Note that versions prior to 4.18 require the 'eval/e' command to be specified.

yq e <exp> <file> {% endhint %}

or example

Running

yq --null-input 'true or false'

will output

true

and example

Running

yq --null-input 'true and false'

will output

false

Matching nodes with select, equals and or

Given a sample.yml file of:

- a: bird
  b: dog
- a: frog
  b: bird
- a: cat
  b: fly

then

yq '[.[] | select(.a == "cat" or .b == "dog")]' sample.yml

will output

- a: bird
  b: dog
- a: cat
  b: fly

any returns true if any boolean in a given array is true

Given a sample.yml file of:

- false
- true

then

yq 'any' sample.yml

will output

true

any returns false for an empty array

Given a sample.yml file of:

[]

then

yq 'any' sample.yml

will output

false

any_c returns true if any element in the array is true for the given condition.

Given a sample.yml file of:

a:
  - rad
  - awesome
b:
  - meh
  - whatever

then

yq '.[] |= any_c(. == "awesome")' sample.yml

will output

a: true
b: false

all returns true if all booleans in a given array are true

Given a sample.yml file of:

- true
- true

then

yq 'all' sample.yml

will output

true

all returns true for an empty array

Given a sample.yml file of:

[]

then

yq 'all' sample.yml

will output

true

all_c returns true if all elements in the array are true for the given condition.

Given a sample.yml file of:

a:
  - rad
  - awesome
b:
  - meh
  - 12

then

yq '.[] |= all_c(tag == "!!str")' sample.yml

will output

a: true
b: false

Not true is false

Running

yq --null-input 'true | not'

will output

false

Not false is true

Running

yq --null-input 'false | not'

will output

true

String values considered to be true

Running

yq --null-input '"cat" | not'

will output

false

Empty string value considered to be true

Running

yq --null-input '"" | not'

will output

false

Numbers are considered to be true

Running

yq --null-input '1 | not'

will output

false

Zero is considered to be true

Running

yq --null-input '0 | not'

will output

false

Null is considered to be false

Running

yq --null-input '~ | not'

will output

true