yq/operators/error.md
2022-07-15 10:45:22 +10:00

1.1 KiB

Error

Use this operation to short-circuit expressions. Useful for validation.

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

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

Validate a particular value

Given a sample.yml file of:

a: hello

then

yq 'select(.a == "howdy") or error(".a [" + .a + "] is not howdy!")' sample.yml

will output

Error: .a [hello] is not howdy!

Validate the environment variable is a number - invalid

Running

numberOfCats="please" yq --null-input 'env(numberOfCats) | select(tag == "!!int") or error("numberOfCats is not a number :(")'

will output

Error: numberOfCats is not a number :(

Validate the environment variable is a number - valid

with can be a convenient way of encapsulating validation.

Given a sample.yml file of:

name: Bob
favouriteAnimal: cat

then

numberOfCats="3" yq '
	with(env(numberOfCats); select(tag == "!!int") or error("numberOfCats is not a number :(")) | 
	.numPets = env(numberOfCats)
' sample.yml

will output

name: Bob
favouriteAnimal: cat
numPets: 3