Skip to content

Commit

Permalink
Add a snippet to suggest using the ? operator for environmental varia…
Browse files Browse the repository at this point in the history
…bles (#1142)

* Add a snippet to suggest using the ? operator for environmental variables

* Add "default" and "in" examples for envvars
  • Loading branch information
132ikl authored Nov 21, 2023
1 parent 2a53464 commit eb28ebb
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions book/environment.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,38 @@ Individual environment variables are fields of a record that is stored in the `$
BAR
```

Sometimes, you may want to access an environmental variable which might be unset. Consider using the [question mark operator](variables_and_subexpressions.md#variable-paths) to avoid an error:
```nu
> $env.FOO | describe
Error: nu::shell::column_not_found
× Cannot find column
╭─[entry #1:1:1]
1 │ $env.FOO
· ──┬─ ─┬─
· │ ╰── cannot find column 'FOO'
· ╰── value originates here
╰────
> $env.FOO? | describe
nothing
> $env.FOO? | default "BAR"
BAR
```

Alternatively, you can check for the presence of an environmental variable with `in`:

```
> $env.FOO
BAR
> if "FOO" in $env {
> echo $env.FOO
> }
BAR
```

## Scoping

When you set an environment variable, it will be available only in the current scope (the block you're in and any block inside of it).
Expand Down

0 comments on commit eb28ebb

Please sign in to comment.