2021-11-03 02:54:09 +00:00
|
|
|
# Alternative (Default value)
|
|
|
|
|
2020-12-21 00:32:34 +00:00
|
|
|
This operator is used to provide alternative (or default) values when a particular expression is either null or false.
|
|
|
|
|
2022-02-06 03:39:46 +00:00
|
|
|
{% hint style="warning" %}
|
|
|
|
Note that versions prior to 4.18 require the 'eval/e' command to be specified. 
|
|
|
|
|
|
|
|
`yq e <exp> <file>`
|
|
|
|
{% endhint %}
|
|
|
|
|
2020-12-21 00:32:34 +00:00
|
|
|
## LHS is defined
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
a: bridge
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-27 06:21:10 +00:00
|
|
|
yq '.a // "hello"' sample.yml
|
2020-12-21 00:32:34 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
bridge
|
|
|
|
```
|
|
|
|
|
|
|
|
## LHS is not defined
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
{}
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-27 06:21:10 +00:00
|
|
|
yq '.a // "hello"' sample.yml
|
2020-12-21 00:32:34 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
hello
|
|
|
|
```
|
|
|
|
|
|
|
|
## LHS is null
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
a: ~
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-27 06:21:10 +00:00
|
|
|
yq '.a // "hello"' sample.yml
|
2020-12-21 00:32:34 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
hello
|
|
|
|
```
|
|
|
|
|
|
|
|
## LHS is false
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
a: false
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-27 06:21:10 +00:00
|
|
|
yq '.a // "hello"' sample.yml
|
2020-12-21 00:32:34 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
hello
|
|
|
|
```
|
|
|
|
|
|
|
|
## RHS is an expression
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
a: false
|
|
|
|
b: cat
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-27 06:21:10 +00:00
|
|
|
yq '.a // .b' sample.yml
|
2020-12-21 00:32:34 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
cat
|
|
|
|
```
|
|
|
|
|
2022-09-09 00:18:49 +00:00
|
|
|
## Update or create - entity exists
|
|
|
|
This initialises `a` if it's not present
|
|
|
|
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
a: 1
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
|
|
|
yq '(.a // (.a = 0)) += 1' sample.yml
|
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
a: 2
|
|
|
|
```
|
|
|
|
|
|
|
|
## Update or create - entity does not exist
|
|
|
|
This initialises `a` if it's not present
|
|
|
|
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
|
|
|
b: camel
|
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
|
|
|
yq '(.a // (.a = 0)) += 1' sample.yml
|
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
|
|
|
b: camel
|
|
|
|
a: 1
|
|
|
|
```
|
|
|
|
|