bgudmestad commited on
Commit
8d756d3
1 Parent(s): 0d4dd97

Upload 60 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
3rdpartyprompts.md ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # How to configure 3rd party prompts
2
+
3
+ ## nerdfonts
4
+
5
+ nerdfonts are not required but they make the presentation much better.
6
+
7
+ [site](https://www.nerdfonts.com)
8
+
9
+ [repo](https://github.com/ryanoasis/nerd-fonts)
10
+
11
+ ## oh-my-posh
12
+
13
+ [site](https://ohmyposh.dev/)
14
+
15
+ [repo](https://github.com/JanDeDobbeleer/oh-my-posh)
16
+
17
+ If you like [oh-my-posh](https://ohmyposh.dev/), you can use oh-my-posh with Nushell with a few steps. It works great with Nushell. How to setup oh-my-posh with Nushell:
18
+
19
+ 1. Install Oh My Posh and download oh-my-posh's themes following [guide](https://ohmyposh.dev/docs/installation/linux).
20
+ 2. Download and install a [nerd font](https://github.com/ryanoasis/nerd-fonts).
21
+ 3. Generate the .oh-my-posh.nu file. By default it will be generated to your home directory. You can use `--config` to specify a theme, other wise, oh-my-posh comes with a default theme.
22
+ 4. Initialize oh-my-posh prompt by adding in ~/.config/nushell/config.nu(or the path output by `$nu.config-path`) to source ~/.oh-my-posh.nu.
23
+
24
+ ```nu
25
+ # Generate the .oh-my-posh.nu file
26
+ > oh-my-posh init nu --config ~/.poshthemes/M365Princess.omp.json
27
+
28
+ # Initialize oh-my-posh.nu at shell startup by adding this line in your config.nu file
29
+ > source ~/.oh-my-posh.nu
30
+ ```
31
+
32
+ For MacOS users:
33
+
34
+ 1. You can install oh-my-posh by `brew`, just following the [guide here](https://ohmyposh.dev/docs/installation/macos)
35
+ 2. Download and install a [nerd font](https://github.com/ryanoasis/nerd-fonts).
36
+ 3. Set the PROMPT_COMMAND in the file output by `$nu.config-path`, here is a code snippet:
37
+
38
+ ```nu
39
+ let posh_dir = (brew --prefix oh-my-posh | str trim)
40
+ let posh_theme = $'($posh_dir)/share/oh-my-posh/themes/'
41
+ # Change the theme names to: zash/space/robbyrussel/powerline/powerlevel10k_lean/
42
+ # material/half-life/lambda Or double lines theme: amro/pure/spaceship, etc.
43
+ # For more [Themes demo](https://ohmyposh.dev/docs/themes)
44
+ $env.PROMPT_COMMAND = { || oh-my-posh prompt print primary --config $'($posh_theme)/zash.omp.json' }
45
+ # Optional
46
+ $env.PROMPT_INDICATOR = $"(ansi y)$> (ansi reset)"
47
+ ```
48
+
49
+ ## Starship
50
+
51
+ [site](https://starship.rs/)
52
+
53
+ [repo](https://github.com/starship/starship)
54
+
55
+ 1. Follow the links above and install Starship.
56
+ 2. Install nerdfonts depending on your preferences.
57
+ 3. Use the config example below. Make sure to set the `STARSHIP_SHELL` environment variable.
58
+
59
+ ::: tip
60
+ An alternate way to enable Starship is described in the [Starship Quick Install](https://starship.rs/#nushell) instructions.
61
+
62
+ The link above is the official integration of Starship and Nushell and is the simplest way to get
63
+ Starship running without doing anything manual:
64
+
65
+ - Starship will create its own configuration / environment setup script
66
+ - you simply have to create it in `env.nu` and `use` it in `config.nu`
67
+ :::
68
+
69
+ Here's an example config section for Starship:
70
+
71
+ ```nu
72
+ $env.STARSHIP_SHELL = "nu"
73
+
74
+ def create_left_prompt [] {
75
+ starship prompt --cmd-duration $env.CMD_DURATION_MS $'--status=($env.LAST_EXIT_CODE)'
76
+ }
77
+
78
+ # Use nushell functions to define your right and left prompt
79
+ $env.PROMPT_COMMAND = { || create_left_prompt }
80
+ $env.PROMPT_COMMAND_RIGHT = ""
81
+
82
+ # The prompt indicators are environmental variables that represent
83
+ # the state of the prompt
84
+ $env.PROMPT_INDICATOR = ""
85
+ $env.PROMPT_INDICATOR_VI_INSERT = ": "
86
+ $env.PROMPT_INDICATOR_VI_NORMAL = "〉"
87
+ $env.PROMPT_MULTILINE_INDICATOR = "::: "
88
+ ```
89
+
90
+ Now restart Nu.
91
+
92
+ ```
93
+ nushell on 📙 main is 📦 v0.60.0 via 🦀 v1.59.0
94
+
95
+ ```
96
+
97
+ ## Purs
98
+
99
+ [repo](https://github.com/xcambar/purs)
README.md ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Introduction
2
+
3
+ Hello, and welcome to the Nushell project.
4
+ The goal of this project is to take the Unix philosophy of shells, where pipes connect simple commands together, and bring it to the modern style of development.
5
+ Thus, rather than being either a shell, or a programming language, Nushell connects both by bringing a rich programming language and a full-featured shell together into one package.
6
+
7
+ Nu takes cues from a lot of familiar territory: traditional shells like bash, object based shells like PowerShell, gradually typed languages like TypeScript, functional programming, systems programming, and more. But rather than trying to be a jack of all trades, Nu focuses its energy on doing a few things well:
8
+
9
+ - Being a flexible cross-platform shell with a modern feel
10
+ - Solving problems as a modern programming language that works with the structure of your data
11
+ - Giving clear error messages and clean IDE support
12
+
13
+ ## This Book
14
+
15
+ The book is split into chapters which are further broken down into sections.
16
+ You can click on the chapter headers to get more information about it.
17
+
18
+ - [Getting Started](getting_started.md) teaches you how to install Nushell and shows you the ropes. It also explains some of the design principles where Nushell differs from typical shells, such as bash.
19
+ - [Nu Fundamentals](nu_fundamentals.md) explains basic concepts of the Nushell language.
20
+ - [Programming in Nu](programming_in_nu.md) dives more deeply into the language features and shows several ways how to organize and structure your code.
21
+ - [Nu as a Shell](nu_as_a_shell.md) focuses on the shell features, most notably the configuration and environment.
22
+ - [Coming to Nu](coming_to_nu.md) is intended to give a quick start for users coming from other shells or languages.
23
+ - [Design Notes](design_notes.md) has in-depth explanation of some of the Nushell's design choices.
24
+ - [(Not So) Advanced](advanced.md) includes some more advanced topics (they are not _so_ advanced, make sure to check them out, too!).
25
+
26
+ ## The Many Parts of Nushell
27
+
28
+ The Nushell project consists of multiple different repositories and subprojects.
29
+ You can find all of them under [our organization on GitHub](https://github.com/nushell).
30
+
31
+ - The main Nushell repository can be found [here](https://github.com/nushell/nushell). It is broken into multiple crates that can be used as independent libraries in your own project, if you wish so.
32
+ - The repository of our [nushell.sh](https://www.nushell.sh) page, including this book, can be found [here](https://github.com/nushell/nushell.github.io).
33
+ - Nushell has its own line editor which [has its own repository](https://github.com/nushell/reedline)
34
+ - [`nu_scripts`](https://github.com/nushell/nu_scripts) is a place to share scripts and modules with other users until we have some sort of package manager.
35
+ - [Nana](https://github.com/nushell/nana) is an experimental effort to explore graphical user interface for Nushell.
36
+ - [Awesome Nu](https://github.com/nushell/awesome-nu) contains a list of tools that work with the Nushell ecosystem: plugins, scripts, editor extension, 3rd party integrations, etc.
37
+ - [Nu Showcase](https://github.com/nushell/showcase) is a place to share works about Nushell, be it blogs, artwork or something else.
38
+ - [Request for Comment (RFC)](https://github.com/nushell/rfcs) serves as a place to propose and discuss major design changes. While currently under-utilized, we expect to use it more as we get closer to and beyond 1.0.
39
+
40
+ ## Contributing
41
+
42
+ We welcome contributions!
43
+ [As you can see](#the-many-parts-of-nushell), there are a lot of places to contribute to.
44
+ Most repositories contain `CONTRIBUTING.md` file with tips and details that should help you get started (if not, consider contributing a fix!).
45
+
46
+ Nushell itself is written in [Rust](https://www.rust-lang.org).
47
+ However, you do not have to be a Rust programmer to help.
48
+ If you know some web development, you can contribute to improving this website or the Nana project.
49
+ [Dataframes](dataframes.md) can use your data processing expertise.
50
+
51
+ If you wrote a cool script, plugin or integrated Nushell somewhere, we'd welcome your contribution to `nu_scripts` or Awesome Nu.
52
+ Discovering bugs with reproduction steps and filing GitHub issues for them is a valuable help, too!
53
+ You can contribute to Nushell just by using Nushell!
54
+
55
+ Since Nushell evolves fast, this book is in a constant need of updating.
56
+ Contributing to this book does not require any special skills aside from a basic familiarity with Markdown.
57
+ Furthermore, you can consider translating parts of it to your language.
58
+
59
+ ## Community
60
+
61
+ The main place to discuss anything Nushell is our [Discord](https://discord.com/invite/NtAbbGn).
62
+ You can also follow us on [Twitter](https://twitter.com/nu_shell) for news and updates.
63
+ Finally, you can use the GitHub discussions or file GitHub issues.
advanced.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (Not So) Advanced
2
+
3
+ While the "Advanced" title might sound daunting and you might be tempted to skip this chapter, in fact, some of the most interesting and powerful features can be found here.
4
+
5
+ Besides the built-in commands, Nushell has a [standard library](standard_library.md).
6
+
7
+ Nushell operates on _structured data_.
8
+ You could say that Nushell is a "data-first" shell and a programming language.
9
+ To further explore the data-centric direction, Nushell includes a full-featured dataframe processing engine using [Polars](https://github.com/pola-rs/polars) as the backend.
10
+ Make sure to check the [Dataframes documentation](dataframes.md) if you want to process large data efficiently directly in your shell.
11
+
12
+ Values in Nushell contain some extra [metadata](metadata.md).
13
+ This metadata can be used, for example, to [create custom errors](creating_errors.md).
14
+
15
+ Thanks to Nushell's strict scoping rules, it is very easy to [iterate over collections in parallel](parallelism.md) which can help you speed up long-running scripts by just typing a few characters.
16
+
17
+ You can [interactively explore data](explore.md) with the [`explore`](/commands/docs/explore.md) command.
18
+
19
+ Finally, you can extend Nushell's functionality with [plugins](plugins.md).
20
+ Almost anything can be a plugin as long as it communicates with Nushell in a protocol that Nushell understands.
aliases.md ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Aliases
2
+
3
+ Aliases in Nushell offer a way of doing a simple replacement of command calls (both external and internal commands). This allows you to create a shorthand name for a longer command, including its default arguments.
4
+
5
+ For example, let's create an alias called `ll` which will expand to `ls -l`.
6
+
7
+ ```nu
8
+ > alias ll = ls -l
9
+ ```
10
+
11
+ We can now call this alias:
12
+
13
+ ```nu
14
+ > ll
15
+ ```
16
+
17
+ Once we do, it's as if we typed `ls -l`. This also allows us to pass in flags or positional parameters. For example, we can now also write:
18
+
19
+ ```nu
20
+ > ll -a
21
+ ```
22
+
23
+ And get the equivalent to having typed `ls -l -a`.
24
+
25
+ ## List all loaded aliases
26
+
27
+ Your useable aliases can be seen in `scope aliases` and `help aliases`.
28
+
29
+ ## Persisting
30
+
31
+ To make your aliases persistent they must be added to your _config.nu_ file by running `config nu` to open an editor and inserting them, and then restarting nushell.
32
+ e.g. with the above `ll` alias, you can add `alias ll = ls -l` anywhere in _config.nu_
33
+
34
+ ```nu
35
+ $env.config = {
36
+ # main configuration
37
+ }
38
+
39
+ alias ll = ls -l
40
+
41
+ # some other config and script loading
42
+ ```
43
+
44
+ ## Piping in aliases
45
+
46
+ Note that `alias uuidgen = uuidgen | tr A-F a-f` (to make uuidgen on mac behave like linux) won't work.
47
+ The solution is to define a command without parameters that calls the system program `uuidgen` via `^`.
48
+
49
+ ```nu
50
+ def uuidgen [] { ^uuidgen | tr A-F a-f }
51
+ ```
52
+
53
+ See more in the [custom commands](custom_commands.md) section of this book.
54
+
55
+ Or a more idiomatic example with nushell internal commands
56
+
57
+ ```nu
58
+ def lsg [] { ls | sort-by type name -i | grid -c | str trim }
59
+ ```
60
+
61
+ displaying all listed files and folders in a grid.
62
+
63
+ ## Replacing existing commands using aliases
64
+
65
+ > Caution! When replacing commands it is best to "back up" the command first and avoid recursion error.
66
+
67
+ How to back up a command like `ls`:
68
+ ```nu
69
+ alias core-ls = ls # This will create a new alias core-ls for ls
70
+ ```
71
+ Now you can use `core-ls` as `ls` in your nu-programming. You will see further down how to use `core-ls`.
72
+
73
+ The reason you need to use alias is because, unlike `def`, aliases are position-dependent. So, you need to "back up" the old command first with an alias, before re-defining it.
74
+ If you do not backup the command and you replace the command using `def` you get a recursion error.
75
+
76
+ ```nu
77
+ def ls [] { ls }; ls # Do *NOT* do this! This will throw a recursion error
78
+
79
+ #output:
80
+ #Error: nu::shell::recursion_limit_reached
81
+ #
82
+ # × Recursion limit (50) reached
83
+ # ╭─[C:\Users\zolodev\AppData\Roaming\nushell\config.nu:807:1]
84
+ # 807 │
85
+ # 808 │ def ls [] { ls }; ls
86
+ # · ───┬──
87
+ # · ╰── This called itself too many times
88
+ # ╰────
89
+ ```
90
+
91
+ The recommended way to replace an existing command is to shadow the command.
92
+ Here is an example shadowing the `ls` command.
93
+
94
+ ```nu
95
+ # An escape hatch to have access to the original ls command
96
+ alias core-ls = ls
97
+
98
+ # Call the built-in ls command with a path parameter
99
+ def old-ls [path] {
100
+ core-ls $path | sort-by type name -i
101
+ }
102
+
103
+ # Shadow the ls command so that you always have the sort type you want
104
+ def ls [path?] {
105
+ if $path == null {
106
+ old-ls .
107
+ } else {
108
+ old-ls $path
109
+ }
110
+ }
111
+ ```
112
+
background_task.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Background tasks with Nu
2
+
3
+ Currently, Nushell doesn't have built-in background task management feature, but you can make it "support" background task with some tools, here are some examples:
4
+
5
+ 1. Using a third-party task management tools, like [pueue](https://github.com/Nukesor/pueue)
6
+ 2. Using a terminal multiplexer, like [tmux](https://github.com/tmux/tmux/wiki) or [zellij](https://zellij.dev/)
7
+
8
+ ## Using nu with pueue
9
+
10
+ The module borrows the power of [pueue](https://github.com/Nukesor/pueue), it is possible to schedule background tasks to pueue, and manage those tasks (such as viewing logs, killing tasks, or getting the running status of all tasks, creating groups, pausing tasks etc etc)
11
+
12
+ Unlike terminal multiplexer, you don't need to attach to multiple tmux sessions, and get task status easily.
13
+
14
+ Here we provide a [nushell module](https://github.com/nushell/nu_scripts/tree/main/modules/background_task) to work with pueue easiler.
15
+
16
+ Here is a setup example to make Nushell "support" background tasks:
17
+
18
+ 1. Install pueue
19
+ 2. run `pueued`, you can refer to [start-the-daemon page](https://github.com/Nukesor/pueue/wiki/Get-started#start-the-daemon) for more information.
20
+ 3. Put the [task.nu](https://github.com/nushell/nu_scripts/blob/main/modules/background_task/task.nu) file under `$env.NU_LIB_DIRS`.
21
+ 4. Add a line to the `$nu.config-path` file: `use task.nu`
22
+ 5. Restart Nushell.
23
+
24
+ Then you will get some commands to schedule background tasks. (e.g: `task spawn`, `task status`, `task log`)
25
+
26
+ Cons: It spawns a new Nushell interpreter to execute every single task, so it doesn't inherit current scope's variables, custom commands, alias definition.
27
+ It only inherits environment variables whose value can be converted to a string.
28
+ Therefore, if you want to use custom commands or variables, you have to [`use`](/commands/docs/use.md) or [`def`](/commands/docs/def.md) them within the given block.
29
+
30
+ ## Using nu with terminal multiplexer
31
+
32
+ You can choose and install a terminal multiplexer and use it.
33
+
34
+ It allows you to easily switch between multiple programs in one terminal, detach them (they continue to run in the background) and reconnect them to a different terminal. As a result, it is very flexible and usable.
cheat_sheet.md ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Nushell cheat sheet
2
+
3
+ ## Data types
4
+
5
+ ```nu
6
+ > "12" | into int
7
+ ```
8
+
9
+ > **converts string to integer**
10
+
11
+ ---
12
+
13
+ ```nu
14
+ > date now | date to-timezone "Europe/London"
15
+ ```
16
+
17
+ > **converts present date to provided time zone**
18
+
19
+ ---
20
+
21
+ ```nu
22
+ > {'name': 'nu', 'stars': 5, 'language': 'Python'} | upsert language 'Rust'
23
+ ```
24
+
25
+ > **updates a record's language and if none is specified inserts provided value**
26
+
27
+ ---
28
+
29
+ ```nu
30
+ > [one two three] | to yaml
31
+ ```
32
+
33
+ > **converts list of strings to yaml**
34
+
35
+ ---
36
+
37
+ ```nu
38
+ > [[framework, language]; [Django, Python] [Lavarel, PHP]]
39
+ ```
40
+
41
+ > **prints the table**
42
+
43
+ ---
44
+
45
+ ```nu
46
+ > [{name: 'Robert' age: 34 position: 'Designer'}
47
+ {name: 'Margaret' age: 30 position: 'Software Developer'}
48
+ {name: 'Natalie' age: 50 position: 'Accountant'}
49
+ ] | select name position
50
+ ```
51
+
52
+ > **selects two columns from the table and prints their values**
53
+
54
+ ## Strings
55
+
56
+ ```nu
57
+ > let name = "Alice"
58
+ > $"greetings, ($name)!"
59
+ ```
60
+
61
+ > **prints `greetings, Alice!`**
62
+
63
+ ---
64
+
65
+ ```nu
66
+ > let string_list = "one,two,three" | split row ","
67
+ $string_list
68
+
69
+ ╭───┬───────╮
70
+ │ 0 │ one │
71
+ │ 1 │ two │
72
+ │ 2 │ three │
73
+ ╰───┴───────╯
74
+ ```
75
+
76
+ > **splits the string with specified delimiter and saves the list to `string_list` variable**
77
+
78
+ ---
79
+
80
+ ```nu
81
+ "Hello, world!" | str contains "o, w"
82
+ ```
83
+
84
+ > **checks if a string contains a substring and returns `boolean`**
85
+
86
+ ---
87
+
88
+ ```nu
89
+ let str_list = [zero one two]
90
+ $str_list | str join ','
91
+ ```
92
+
93
+ > **joins the list of strings using provided delimiter**
94
+
95
+ ---
96
+
97
+ ```nu
98
+ > 'Hello World!' | str substring 4..8
99
+ ```
100
+
101
+ > **created a slice from a given string with start (4) and end (8) indices**
102
+
103
+ ---
104
+
105
+ ```nu
106
+ > 'Nushell 0.80' | parse '{shell} {version}'
107
+
108
+ ╭───┬─────────┬─────────╮
109
+ │ # │ shell │ version │
110
+ ├───┼─────────┼─────────┤
111
+ │ 0 │ Nushell │ 0.80 │
112
+ ╰───┴─────────┴─────────╯
113
+ ```
114
+
115
+ > **parses the string to columns**
116
+
117
+ ```nu
118
+ > "acronym,long\nAPL,A Programming Language" | from csv
119
+ ```
120
+
121
+ > **parses comma separated values (csv)**
122
+
123
+ ```nu
124
+ > $'(ansi purple_bold)This text is a bold purple!(ansi reset)'
125
+ ```
126
+
127
+ > **ansi command colors the text (alsways end with `ansi reset` to reset color to default)**
128
+
129
+ ## Lists
130
+
131
+ ```nu
132
+ > [foo bar baz] | insert 1 'beeze'
133
+
134
+ ╭───┬───────╮
135
+ │ 0 │ foo │
136
+ │ 1 │ beeze │
137
+ │ 2 │ bar │
138
+ │ 3 │ baz │
139
+ ╰───┴───────╯
140
+ ```
141
+
142
+ > **inserts `beeze` value at st index in the list**
143
+
144
+ ---
145
+
146
+ ```nu
147
+ > [1, 2, 3, 4] | update 1 10
148
+ ```
149
+
150
+ > **updates 2nd value to 10**
151
+
152
+ ---
153
+
154
+ ```nu
155
+ > let numbers = [1, 2, 3, 4, 5]
156
+ > $numbers | prepend 0
157
+ ```
158
+
159
+ > **adds value at the beginning of the list**
160
+
161
+ ---
162
+
163
+ ```nu
164
+ > let numbers = [1, 2, 3, 4, 5]
165
+ > $numbers | append 6
166
+ ```
167
+
168
+ > **adds value at the end of the list**
169
+
170
+ ---
171
+
172
+ ```nu
173
+ > let flowers = [cammomile marigold rose forget-me-not]
174
+ > let flowers = ($flowers | first 2)
175
+ > $flowers
176
+ ```
177
+
178
+ > **creates slice of first two values from `flowers` list**
179
+
180
+ ---
181
+
182
+ ```nu
183
+ > let planets = [Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune]
184
+ > $planets | each { |it| $"($it) is a planet of solar system" }
185
+ ```
186
+
187
+ > **iterates over a list; `it` is current list value**
188
+
189
+ ---
190
+
191
+ ```nu
192
+ > $planets | enumerate | each { |it| $"($it.index + 1) - ($it.item)" }
193
+ ```
194
+
195
+ > **iterates over a list and provides index and value in `it`**
196
+
197
+ ---
198
+
199
+ ```nu
200
+ > let scores = [3 8 4]
201
+ > $"total = ($scores | reduce { |it, acc| $acc + $it })"
202
+ ```
203
+
204
+ > **reduces the list to a single value, `reduce` gives access to accumulator that is applied
205
+ > to each element in the list**
206
+
207
+ ---
208
+
209
+ ```nu
210
+ > $"total = ($scores | reduce --fold 1 { |it, acc| $acc * $it })"
211
+ ```
212
+
213
+ > **initial value for accumulator value can be set with `--fold`**
214
+
215
+ ---
216
+
217
+ ```nu
218
+ > let planets = [Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune]
219
+ > $planets.2
220
+ > Earth
221
+ ```
222
+
223
+ > **gives access to the 3rd item in the list**
224
+
225
+ ---
226
+
227
+ ```nu
228
+ > let planets = [Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune]
229
+ > $planets | any {|it| $it | str starts-with "E" }
230
+ > true
231
+ ```
232
+
233
+ > **checks if any string in the list starts with `E`**
234
+
235
+ ---
236
+
237
+ ```nu
238
+ > let cond = {|x| $x < 0 }; [-1 -2 9 1] | take while $cond
239
+ ╭───┬────╮
240
+ │ 0 │ -1 │
241
+ │ 1 │ -2 │
242
+ ╰───┴────╯
243
+ ```
244
+
245
+ > **creates slice of items that satisfy provided condition**
246
+
247
+ ## Tables
248
+
249
+ ```nu
250
+ > ls | sort-by size
251
+ ```
252
+
253
+ > **sorting table by size of files**
254
+
255
+ ---
256
+
257
+ ```nu
258
+ > ls | sort-by size | first 5
259
+ ```
260
+
261
+ > **sorting table by size of files and show first 5 entries**
262
+
263
+ ---
264
+
265
+ ```nu
266
+ > let $a = [[first_column second_column third_column]; [foo bar snooze]]
267
+ > let $b = [[first_column second_column third_column]; [hex seeze feeze]]
268
+ > $a | append $b
269
+
270
+ ╭───┬──────────────┬───────────────┬──────────────╮
271
+ │ # │ first_column │ second_column │ third_column │
272
+ ├───┼──────────────┼───────────────┼──────────────┤
273
+ │ 0 │ foo │ bar │ snooze │
274
+ │ 1 │ hex │ seeze │ feeze │
275
+ ╰───┴──────────────┴───────────────┴──────────────╯
276
+ ```
277
+
278
+ > **concatenate two tables with same columns**
279
+
280
+ ---
281
+
282
+ ```nu
283
+ > let teams_scores = [[team score plays]; ['Boston Celtics' 311 3] ['Golden State Warriors', 245 2]]
284
+ > $teams_scores | drop column
285
+
286
+ ╭───┬───────────────────────┬───────╮
287
+ │ # │ team │ score │
288
+ ├───┼───────────────────────┼───────┤
289
+ │ 0 │ Boston Celtics │ 311 │
290
+ │ 1 │ Golden State Warriors │ 245 │
291
+ ╰───┴───────────────────────┴───────╯
292
+ ```
293
+
294
+ > **remove the last column of a table**
295
+
296
+ ## Files & Filesystem
297
+
298
+ ```nu
299
+ > start file.txt
300
+ ```
301
+
302
+ > **opens a text file with the default text editor**
303
+
304
+ ---
305
+
306
+ ```nu
307
+ > 'lorem ipsum ' | save file.txt
308
+ ```
309
+
310
+ > **saves a string to text file**
311
+
312
+ ---
313
+
314
+ ```nu
315
+ > 'dolor sit amet' | save --append file.txt
316
+ ```
317
+
318
+ > **appends a string to the end of file.txt**
319
+
320
+ ---
321
+
322
+ ```nu
323
+ > { a: 1, b: 2 } | save file.json
324
+ ```
325
+
326
+ > **saves a record to file.json**
327
+
328
+ ---
329
+
330
+ ```nu
331
+ > glob **/*.{rs,toml} --depth 2
332
+ ```
333
+
334
+ > **searches for `.rs` and `.toml` files recursively up to 2 folders deep**
335
+
336
+ ---
337
+
338
+ ```nu
339
+ > watch . --glob=**/*.rs {|| cargo test }
340
+ ```
341
+
342
+ > **runs cargo test whenever a Rust file changes**
343
+
344
+ ---
345
+
346
+ ## Custom Commands
347
+
348
+ ```nu
349
+ def greet [name: string] {
350
+ $"hello ($name­)"
351
+ }
352
+ ```
353
+
354
+ > **custom command with parameter type set to string**
355
+
356
+ ---
357
+
358
+ ```nu
359
+ def greet [name = "nushell"] {
360
+ $"hello ($name­)"
361
+ }
362
+ ```
363
+
364
+ > **custom command with default parameter set to nushell**
365
+
366
+ ---
367
+
368
+ ```nu
369
+ def greet [
370
+ name: string
371
+ --age: int
372
+ ] {
373
+ [$name $age]
374
+ }
375
+
376
+ > greet world --age 10
377
+ ```
378
+
379
+ > **passing named parameter by defining flag for custom commands**
380
+
381
+ ---
382
+
383
+ ```nu
384
+ def greet [
385
+ name: string
386
+ --age (-a): int
387
+ --twice
388
+ ] {
389
+ if $twice {
390
+ [$name $age $name $age]
391
+ } else {
392
+ [$name $age]
393
+ }
394
+ }
395
+ > greet -a 10 --twice hello
396
+ ```
397
+
398
+ > **using flag as a switch with a shorthand flag (-a) for the age**
399
+
400
+ ---
401
+
402
+ ```nu
403
+ def greet [...name: string] {
404
+ print "­hello all:"
405
+ for $n in $name {
406
+ print $n
407
+ }
408
+ }
409
+
410
+ > greet earth mars jupiter venus
411
+ ```
412
+
413
+ > **custom command which takes any number of positional arguments using rest params**
414
+
415
+ ## Variables & Subexpressions
416
+
417
+ ```nu
418
+ > let val = 42
419
+ > print $val
420
+ 42
421
+ ```
422
+
423
+ > **an immutable variable cannot change its value after declaration**
424
+
425
+ ---
426
+
427
+ ```nu
428
+ > let val = 42
429
+ > do { let val = 101; $val }
430
+ 101
431
+ > $val
432
+ 42
433
+ ```
434
+
435
+ > **shadowing variable (declaring variable with the same name in a different scope)**
436
+
437
+ ---
438
+
439
+ ```nu
440
+ > mut val = 42
441
+ > $val += 27
442
+ > $val
443
+ 69
444
+ ```
445
+
446
+ > **declaring a mutable variable with mut key word**
447
+
448
+ ---
449
+
450
+ ```nu
451
+ > mut x = 0
452
+ > [1 2 3] | each { $x += 1 }
453
+ ```
454
+
455
+ > **closures and nested defs cannot capture mutable variables from their enviro­nment.
456
+ > This expression results in error.**
457
+
458
+ ```nu
459
+ > const plugin = 'path/­to/­plugin'
460
+ > register $plugin
461
+ ```
462
+
463
+ > **a constant variable is immutable value which is fully evaluated at parse-time**
464
+
465
+ ---
466
+
467
+ ```nu
468
+ > let files = (ls)
469
+ > $files.na­me?.0?
470
+ ```
471
+
472
+ > **using question mark operator to return null instead of error if provided path is incorrect**
473
+
474
+ ---
475
+
476
+ ```nu
477
+ > let big_files = (ls | where size > 10kb)
478
+ > $big_files
479
+ ```
480
+
481
+ > **using subexp­ression by wrapping the expression with parent­heses ()**
482
+
483
+ ---
484
+
485
+ ## Modules
486
+
487
+ ```nu
488
+ > module greetings {
489
+ export def hello [name: string] {
490
+ $"hello ($name­)!"
491
+ }
492
+
493
+ export def hi [where: string] {
494
+ $"hi ($where)!­"
495
+ }
496
+ }
497
+
498
+ > use greetings hello
499
+ > hello "­wor­ld"
500
+ ```
501
+
502
+ > **using inline module**
503
+
504
+ ---
505
+
506
+ ```nu
507
+ # greeti­ngs.nu
508
+ export-env {
509
+ $env.M­YNAME = "­Arthur, King of the Briton­s"
510
+ }
511
+ export def hello [] {
512
+ $"hello ($env.M­YN­AME­)"
513
+ }
514
+
515
+ > use greeti­ngs.nu
516
+ > $env.M­YNAME
517
+ Arthur, King of the Britons
518
+ > greetings hello
519
+ hello Arthur, King of the Britons!
520
+ ```
521
+
522
+ > **importing module from file and using its enviro­nment in current scope**
523
+
524
+ ---
525
+
526
+ ```nu
527
+ # greeti­ngs.nu
528
+ export def hello [name: string] {
529
+ $"hello ($name­)!"
530
+ }
531
+
532
+ export def hi [where: string] {
533
+ $"hi ($where)!­"
534
+ }
535
+
536
+ export def main [] {
537
+ "­gre­etings and salutations!"
538
+ }
539
+
540
+ > use greeti­ngs.nu
541
+ > greetings
542
+ greetings and saluta­tions!
543
+ > greetings hello world
544
+ hello world!
545
+ ```
546
+
547
+ > **using main command in module**
548
+
549
+ ---
coloring_and_theming.md ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Coloring and Theming in Nu
2
+
3
+ Many parts of Nushell's interface can have their color customized. All of these can be set in the `config.nu` configuration file. If you see the hash/hashtag/pound mark `#` in the config file it means the text after it is commented out.
4
+
5
+ 1. table borders
6
+ 2. primitive values
7
+ 3. shapes (this is the command line syntax)
8
+ 4. prompt
9
+ 5. LS_COLORS
10
+
11
+ ## `Table borders`
12
+
13
+ Table borders are controlled by the `$env.config.table.mode` setting in `config.nu`. Here is an example:
14
+
15
+ ```nu
16
+ > $env.config = {
17
+ table: {
18
+ mode: rounded
19
+ }
20
+ }
21
+ ```
22
+
23
+ Here are the current options for `$env.config.table.mode`:
24
+
25
+ - `rounded` # of course, this is the best one :)
26
+ - `basic`
27
+ - `compact`
28
+ - `compact_double`
29
+ - `light`
30
+ - `thin`
31
+ - `with_love`
32
+ - `reinforced`
33
+ - `heavy`
34
+ - `none`
35
+ - `other`
36
+
37
+ ### `Color symbologies`
38
+
39
+ ---
40
+
41
+ - `r` - normal color red's abbreviation
42
+ - `rb` - normal color red's abbreviation with bold attribute
43
+ - `red` - normal color red
44
+ - `red_bold` - normal color red with bold attribute
45
+ - `"#ff0000"` - "#hex" format foreground color red (quotes are required)
46
+ - `{ fg: "#ff0000" bg: "#0000ff" attr: b }` - "full #hex" format foreground red in "#hex" format with a background of blue in "#hex" format with an attribute of bold abbreviated.
47
+
48
+ ### `attributes`
49
+
50
+ ---
51
+
52
+ | code | meaning |
53
+ | ---- | ------------------- |
54
+ | l | blink |
55
+ | b | bold |
56
+ | d | dimmed |
57
+ | h | hidden |
58
+ | i | italic |
59
+ | r | reverse |
60
+ | s | strikethrough |
61
+ | u | underline |
62
+ | n | nothing |
63
+ | | defaults to nothing |
64
+
65
+ ### `normal colors` and `abbreviations`
66
+
67
+ | code | name |
68
+ | ------ | ---------------------- |
69
+ | g | green |
70
+ | gb | green_bold |
71
+ | gu | green_underline |
72
+ | gi | green_italic |
73
+ | gd | green_dimmed |
74
+ | gr | green_reverse |
75
+ | gbl | green_blink |
76
+ | gst | green_strike |
77
+ | lg | light_green |
78
+ | lgb | light_green_bold |
79
+ | lgu | light_green_underline |
80
+ | lgi | light_green_italic |
81
+ | lgd | light_green_dimmed |
82
+ | lgr | light_green_reverse |
83
+ | lgbl | light_green_blink |
84
+ | lgst | light_green_strike |
85
+ | r | red |
86
+ | rb | red_bold |
87
+ | ru | red_underline |
88
+ | ri | red_italic |
89
+ | rd | red_dimmed |
90
+ | rr | red_reverse |
91
+ | rbl | red_blink |
92
+ | rst | red_strike |
93
+ | lr | light_red |
94
+ | lrb | light_red_bold |
95
+ | lru | light_red_underline |
96
+ | lri | light_red_italic |
97
+ | lrd | light_red_dimmed |
98
+ | lrr | light_red_reverse |
99
+ | lrbl | light_red_blink |
100
+ | lrst | light_red_strike |
101
+ | u | blue |
102
+ | ub | blue_bold |
103
+ | uu | blue_underline |
104
+ | ui | blue_italic |
105
+ | ud | blue_dimmed |
106
+ | ur | blue_reverse |
107
+ | ubl | blue_blink |
108
+ | ust | blue_strike |
109
+ | lu | light_blue |
110
+ | lub | light_blue_bold |
111
+ | luu | light_blue_underline |
112
+ | lui | light_blue_italic |
113
+ | lud | light_blue_dimmed |
114
+ | lur | light_blue_reverse |
115
+ | lubl | light_blue_blink |
116
+ | lust | light_blue_strike |
117
+ | b | black |
118
+ | bb | black_bold |
119
+ | bu | black_underline |
120
+ | bi | black_italic |
121
+ | bd | black_dimmed |
122
+ | br | black_reverse |
123
+ | bbl | black_blink |
124
+ | bst | black_strike |
125
+ | ligr | light_gray |
126
+ | ligrb | light_gray_bold |
127
+ | ligru | light_gray_underline |
128
+ | ligri | light_gray_italic |
129
+ | ligrd | light_gray_dimmed |
130
+ | ligrr | light_gray_reverse |
131
+ | ligrbl | light_gray_blink |
132
+ | ligrst | light_gray_strike |
133
+ | y | yellow |
134
+ | yb | yellow_bold |
135
+ | yu | yellow_underline |
136
+ | yi | yellow_italic |
137
+ | yd | yellow_dimmed |
138
+ | yr | yellow_reverse |
139
+ | ybl | yellow_blink |
140
+ | yst | yellow_strike |
141
+ | ly | light_yellow |
142
+ | lyb | light_yellow_bold |
143
+ | lyu | light_yellow_underline |
144
+ | lyi | light_yellow_italic |
145
+ | lyd | light_yellow_dimmed |
146
+ | lyr | light_yellow_reverse |
147
+ | lybl | light_yellow_blink |
148
+ | lyst | light_yellow_strike |
149
+ | p | purple |
150
+ | pb | purple_bold |
151
+ | pu | purple_underline |
152
+ | pi | purple_italic |
153
+ | pd | purple_dimmed |
154
+ | pr | purple_reverse |
155
+ | pbl | purple_blink |
156
+ | pst | purple_strike |
157
+ | lp | light_purple |
158
+ | lpb | light_purple_bold |
159
+ | lpu | light_purple_underline |
160
+ | lpi | light_purple_italic |
161
+ | lpd | light_purple_dimmed |
162
+ | lpr | light_purple_reverse |
163
+ | lpbl | light_purple_blink |
164
+ | lpst | light_purple_strike |
165
+ | c | cyan |
166
+ | cb | cyan_bold |
167
+ | cu | cyan_underline |
168
+ | ci | cyan_italic |
169
+ | cd | cyan_dimmed |
170
+ | cr | cyan_reverse |
171
+ | cbl | cyan_blink |
172
+ | cst | cyan_strike |
173
+ | lc | light_cyan |
174
+ | lcb | light_cyan_bold |
175
+ | lcu | light_cyan_underline |
176
+ | lci | light_cyan_italic |
177
+ | lcd | light_cyan_dimmed |
178
+ | lcr | light_cyan_reverse |
179
+ | lcbl | light_cyan_blink |
180
+ | lcst | light_cyan_strike |
181
+ | w | white |
182
+ | wb | white_bold |
183
+ | wu | white_underline |
184
+ | wi | white_italic |
185
+ | wd | white_dimmed |
186
+ | wr | white_reverse |
187
+ | wbl | white_blink |
188
+ | wst | white_strike |
189
+ | dgr | dark_gray |
190
+ | dgrb | dark_gray_bold |
191
+ | dgru | dark_gray_underline |
192
+ | dgri | dark_gray_italic |
193
+ | dgrd | dark_gray_dimmed |
194
+ | dgrr | dark_gray_reverse |
195
+ | dgrbl | dark_gray_blink |
196
+ | dgrst | dark_gray_strike |
197
+
198
+ ### `"#hex"` format
199
+
200
+ ---
201
+
202
+ The "#hex" format is one way you typically see colors represented. It's simply the `#` character followed by 6 characters. The first two are for `red`, the second two are for `green`, and the third two are for `blue`. It's important that this string be surrounded in quotes, otherwise Nushell thinks it's a commented out string.
203
+
204
+ Example: The primary `red` color is `"#ff0000"` or `"#FF0000"`. Upper and lower case in letters shouldn't make a difference.
205
+
206
+ This `"#hex"` format allows us to specify 24-bit truecolor tones to different parts of Nushell.
207
+
208
+ ## `full "#hex"` format
209
+
210
+ ---
211
+
212
+ The `full "#hex"` format is a take on the `"#hex"` format but allows one to specify the foreground, background, and attributes in one line.
213
+
214
+ Example: `{ fg: "#ff0000" bg: "#0000ff" attr: b }`
215
+
216
+ - foreground of red in "#hex" format
217
+ - background of blue in "#hex" format
218
+ - attribute of bold abbreviated
219
+
220
+ ## `Primitive values`
221
+
222
+ ---
223
+
224
+ Primitive values are things like `int` and `string`. Primitive values and shapes can be set with a variety of color symbologies seen above.
225
+
226
+ This is the current list of primitives. Not all of these are configurable. The configurable ones are marked with \*.
227
+
228
+ | primitive | default color | configurable |
229
+ | ------------ | --------------------- | ------------ |
230
+ | `any` | | |
231
+ | `binary` | Color::White.normal() | \* |
232
+ | `block` | Color::White.normal() | \* |
233
+ | `bool` | Color::White.normal() | \* |
234
+ | `cellpath` | Color::White.normal() | \* |
235
+ | `condition` | | |
236
+ | `custom` | | |
237
+ | `date` | Color::White.normal() | \* |
238
+ | `duration` | Color::White.normal() | \* |
239
+ | `expression` | | |
240
+ | `filesize` | Color::White.normal() | \* |
241
+ | `float` | Color::White.normal() | \* |
242
+ | `glob` | | |
243
+ | `import` | | |
244
+ | `int` | Color::White.normal() | \* |
245
+ | `list` | Color::White.normal() | \* |
246
+ | `nothing` | Color::White.normal() | \* |
247
+ | `number` | | |
248
+ | `operator` | | |
249
+ | `path` | | |
250
+ | `range` | Color::White.normal() | \* |
251
+ | `record` | Color::White.normal() | \* |
252
+ | `signature` | | |
253
+ | `string` | Color::White.normal() | \* |
254
+ | `table` | | |
255
+ | `var` | | |
256
+ | `vardecl` | | |
257
+ | `variable` | | |
258
+
259
+ #### special "primitives" (not really primitives but they exist solely for coloring)
260
+
261
+ | primitive | default color | configurable |
262
+ | --------------------------- | -------------------------- | ------------ |
263
+ | `leading_trailing_space_bg` | Color::Rgb(128, 128, 128)) | \* |
264
+ | `header` | Color::Green.bold() | \* |
265
+ | `empty` | Color::Blue.normal() | \* |
266
+ | `row_index` | Color::Green.bold() | \* |
267
+ | `hints` | Color::DarkGray.normal() | \* |
268
+
269
+ Here's a small example of changing some of these values.
270
+
271
+ ```nu
272
+ > let config = {
273
+ color_config: {
274
+ separator: purple
275
+ leading_trailing_space_bg: "#ffffff"
276
+ header: gb
277
+ date: wd
278
+ filesize: c
279
+ row_index: cb
280
+ bool: red
281
+ int: green
282
+ duration: blue_bold
283
+ range: purple
284
+ float: red
285
+ string: white
286
+ nothing: red
287
+ binary: red
288
+ cellpath: cyan
289
+ hints: dark_gray
290
+ }
291
+ }
292
+ ```
293
+
294
+ Here's another small example using multiple color syntaxes with some comments.
295
+
296
+ ```nu
297
+ > let config = {
298
+ color_config: {
299
+ separator: "#88b719" # this sets only the foreground color like PR #486
300
+ leading_trailing_space_bg: white # this sets only the foreground color in the original style
301
+ header: { # this is like PR #489
302
+ fg: "#B01455", # note, quotes are required on the values with hex colors
303
+ bg: "#ffb900", # note, commas are not required, it could also be all on one line
304
+ attr: bli # note, there are no quotes around this value. it works with or without quotes
305
+ }
306
+ date: "#75507B"
307
+ filesize: "#729fcf"
308
+ row_index: {
309
+ # note, that this is another way to set only the foreground, no need to specify bg and attr
310
+ fg: "#e50914"
311
+ }
312
+ }
313
+ }
314
+ ```
315
+
316
+ ## `Shape` values
317
+
318
+ As mentioned above, `shape` is a term used to indicate the syntax coloring.
319
+
320
+ Here's the current list of flat shapes.
321
+
322
+ | shape | default style | configurable |
323
+ | ---------------------------- | -------------------------------------- | ------------ |
324
+ | `shape_block` | fg(Color::Blue).bold() | \* |
325
+ | `shape_bool` | fg(Color::LightCyan) | \* |
326
+ | `shape_custom` | bold() | \* |
327
+ | `shape_external` | fg(Color::Cyan) | \* |
328
+ | `shape_externalarg` | fg(Color::Green).bold() | \* |
329
+ | `shape_filepath` | fg(Color::Cyan) | \* |
330
+ | `shape_flag` | fg(Color::Blue).bold() | \* |
331
+ | `shape_float` | fg(Color::Purple).bold() | \* |
332
+ | `shape_garbage` | fg(Color::White).on(Color::Red).bold() | \* |
333
+ | `shape_globpattern` | fg(Color::Cyan).bold() | \* |
334
+ | `shape_int` | fg(Color::Purple).bold() | \* |
335
+ | `shape_internalcall` | fg(Color::Cyan).bold() | \* |
336
+ | `shape_list` | fg(Color::Cyan).bold() | \* |
337
+ | `shape_literal` | fg(Color::Blue) | \* |
338
+ | `shape_nothing` | fg(Color::LightCyan) | \* |
339
+ | `shape_operator` | fg(Color::Yellow) | \* |
340
+ | `shape_range` | fg(Color::Yellow).bold() | \* |
341
+ | `shape_record` | fg(Color::Cyan).bold() | \* |
342
+ | `shape_signature` | fg(Color::Green).bold() | \* |
343
+ | `shape_string` | fg(Color::Green) | \* |
344
+ | `shape_string_interpolation` | fg(Color::Cyan).bold() | \* |
345
+ | `shape_table` | fg(Color::Blue).bold() | \* |
346
+ | `shape_variable` | fg(Color::Purple) | \* |
347
+
348
+ Here's a small example of how to apply color to these items. Anything not specified will receive the default color.
349
+
350
+ ```nu
351
+ > $env.config = {
352
+ color_config: {
353
+ shape_garbage: { fg: "#FFFFFF" bg: "#FF0000" attr: b}
354
+ shape_bool: green
355
+ shape_int: { fg: "#0000ff" attr: b}
356
+ }
357
+ }
358
+ ```
359
+
360
+ ## `Prompt` configuration and coloring
361
+
362
+ The Nushell prompt is configurable through these environment variables and config items:
363
+
364
+ - `PROMPT_COMMAND`: Code to execute for setting up the prompt (block)
365
+ - `PROMPT_COMMAND_RIGHT`: Code to execute for setting up the _RIGHT_ prompt (block) (see oh-my.nu in nu_scripts)
366
+ - `PROMPT_INDICATOR` = "〉": The indicator printed after the prompt (by default ">"-like Unicode symbol)
367
+ - `PROMPT_INDICATOR_VI_INSERT` = ": "
368
+ - `PROMPT_INDICATOR_VI_NORMAL` = "v "
369
+ - `PROMPT_MULTILINE_INDICATOR` = "::: "
370
+ - `render_right_prompt_on_last_line`: Bool value to enable or disable the right prompt to be rendered on the last line of the prompt
371
+
372
+ Example: For a simple prompt one could do this. Note that `PROMPT_COMMAND` requires a `block` whereas the others require a `string`.
373
+
374
+ ```nu
375
+ > $env.PROMPT_COMMAND = { build-string (date now | format date '%m/%d/%Y %I:%M:%S%.3f') ': ' (pwd | path basename) }
376
+ ```
377
+
378
+ If you don't like the default `PROMPT_INDICATOR` you could change it like this.
379
+
380
+ ```nu
381
+ > $env.PROMPT_INDICATOR = "> "
382
+ ```
383
+
384
+ If you're using `starship`, you'll most likely want to show the right prompt on the last line of the prompt, just like zsh or fish. You could modify the `config.nu` file, just set `render_right_prompt_on_last_line` to true:
385
+
386
+ ```nu
387
+ config {
388
+ render_right_prompt_on_last_line = true
389
+ ...
390
+ }
391
+ ```
392
+
393
+ Coloring of the prompt is controlled by the `block` in `PROMPT_COMMAND` where you can write your own custom prompt. We've written a slightly fancy one that has git statuses located in the [nu_scripts repo](https://github.com/nushell/nu_scripts/blob/main/modules/prompt/oh-my.nu).
394
+
395
+ ### Transient prompt
396
+
397
+ If you want a different prompt displayed for previously entered commands, you can use Nushell's transient prompt feature. This can be useful if your prompt has lots of information that is unnecessary to show for previous lines (e.g. time and Git status), since you can make it so that previous lines show with a shorter prompt.
398
+
399
+ Each of the `PROMPT_*` variables has a corresponding `TRANSIENT_PROMPT_*` variable to be used for changing that segment when displaying past prompts: `TRANSIENT_PROMPT_COMMAND`, `TRANSIENT_PROMPT_COMMAND_RIGHT`, `TRANSIENT_PROMPT_INDICATOR`, `TRANSIENT_PROMPT_INDICATOR_VI_INSERT`, `TRANSIENT_PROMPT_INDICATOR_VI_NORMAL`, `TRANSIENT_PROMPT_MULTILINE_INDICATOR`. By default, the `PROMPT_*` variables are used for displaying past prompts.
400
+
401
+ For example, if you want to make past prompts show up without a left prompt entirely and leave only the indicator, you can use:
402
+
403
+ ```nu
404
+ > $env.TRANSIENT_PROMPT_COMMAND = ""
405
+ ```
406
+
407
+ If you want to go back to the normal left prompt, you'll have to unset `TRANSIENT_PROMPT_COMMAND`:
408
+
409
+ ```nu
410
+ > hide-env TRANSIENT_PROMPT_COMMAND
411
+ ```
412
+
413
+ ## `LS_COLORS` colors for the [`ls`](/commands/docs/ls.md) command
414
+
415
+ Nushell will respect and use the `LS_COLORS` environment variable setting on Mac, Linux, and Windows. This setting allows you to define the color of file types when you do a [`ls`](/commands/docs/ls.md). For instance, you can make directories one color, _.md markdown files another color, _.toml files yet another color, etc. There are a variety of ways to color your file types.
416
+
417
+ There's an exhaustive list [here](https://github.com/trapd00r/LS_COLORS), which is overkill, but gives you an rudimentary understanding of how to create a ls_colors file that `dircolors` can turn into a `LS_COLORS` environment variable.
418
+
419
+ [This](https://www.linuxhowto.net/how-to-set-colors-for-ls-command/) is a pretty good introduction to `LS_COLORS`. I'm sure you can find many more tutorials on the web.
420
+
421
+ I like the `vivid` application and currently have it configured in my `config.nu` like this. You can find `vivid` [here](https://github.com/sharkdp/vivid).
422
+
423
+ `$env.LS_COLORS = (vivid generate molokai | str trim)`
424
+
425
+ If `LS_COLORS` is not set, nushell will default to a built-in `LS_COLORS` setting, based on 8-bit (extended) ANSI colors.
426
+
427
+ ## Theming
428
+
429
+ Theming combines all the coloring above. Here's a quick example of one we put together quickly to demonstrate the ability to theme. This is a spin on the `base16` themes that we see so widespread on the web.
430
+
431
+ The key to making theming work is to make sure you specify all themes and colors you're going to use in the `config.nu` file _before_ you declare the `let config = ` line.
432
+
433
+ ```nu
434
+ # let's define some colors
435
+
436
+ let base00 = "#181818" # Default Background
437
+ let base01 = "#282828" # Lighter Background (Used for status bars, line number and folding marks)
438
+ let base02 = "#383838" # Selection Background
439
+ let base03 = "#585858" # Comments, Invisibles, Line Highlighting
440
+ let base04 = "#b8b8b8" # Dark Foreground (Used for status bars)
441
+ let base05 = "#d8d8d8" # Default Foreground, Caret, Delimiters, Operators
442
+ let base06 = "#e8e8e8" # Light Foreground (Not often used)
443
+ let base07 = "#f8f8f8" # Light Background (Not often used)
444
+ let base08 = "#ab4642" # Variables, XML Tags, Markup Link Text, Markup Lists, Diff Deleted
445
+ let base09 = "#dc9656" # Integers, Boolean, Constants, XML Attributes, Markup Link Url
446
+ let base0a = "#f7ca88" # Classes, Markup Bold, Search Text Background
447
+ let base0b = "#a1b56c" # Strings, Inherited Class, Markup Code, Diff Inserted
448
+ let base0c = "#86c1b9" # Support, Regular Expressions, Escape Characters, Markup Quotes
449
+ let base0d = "#7cafc2" # Functions, Methods, Attribute IDs, Headings
450
+ let base0e = "#ba8baf" # Keywords, Storage, Selector, Markup Italic, Diff Changed
451
+ let base0f = "#a16946" # Deprecated, Opening/Closing Embedded Language Tags, e.g. <?php ?>
452
+
453
+ # we're creating a theme here that uses the colors we defined above.
454
+
455
+ let base16_theme = {
456
+ separator: $base03
457
+ leading_trailing_space_bg: $base04
458
+ header: $base0b
459
+ date: $base0e
460
+ filesize: $base0d
461
+ row_index: $base0c
462
+ bool: $base08
463
+ int: $base0b
464
+ duration: $base08
465
+ range: $base08
466
+ float: $base08
467
+ string: $base04
468
+ nothing: $base08
469
+ binary: $base08
470
+ cellpath: $base08
471
+ hints: dark_gray
472
+
473
+ # shape_garbage: { fg: $base07 bg: $base08 attr: b} # base16 white on red
474
+ # but i like the regular white on red for parse errors
475
+ shape_garbage: { fg: "#FFFFFF" bg: "#FF0000" attr: b}
476
+ shape_bool: $base0d
477
+ shape_int: { fg: $base0e attr: b}
478
+ shape_float: { fg: $base0e attr: b}
479
+ shape_range: { fg: $base0a attr: b}
480
+ shape_internalcall: { fg: $base0c attr: b}
481
+ shape_external: $base0c
482
+ shape_externalarg: { fg: $base0b attr: b}
483
+ shape_literal: $base0d
484
+ shape_operator: $base0a
485
+ shape_signature: { fg: $base0b attr: b}
486
+ shape_string: $base0b
487
+ shape_filepath: $base0d
488
+ shape_globpattern: { fg: $base0d attr: b}
489
+ shape_variable: $base0e
490
+ shape_flag: { fg: $base0d attr: b}
491
+ shape_custom: {attr: b}
492
+ }
493
+
494
+ # now let's apply our regular config settings but also apply the "color_config:" theme that we specified above.
495
+
496
+ let config = {
497
+ filesize_metric: true
498
+ table_mode: rounded # basic, compact, compact_double, light, thin, with_love, rounded, reinforced, heavy, none, other
499
+ use_ls_colors: true
500
+ color_config: $base16_theme # <-- this is the theme
501
+ use_grid_icons: true
502
+ footer_mode: always #always, never, number_of_rows, auto
503
+ animate_prompt: false
504
+ float_precision: 2
505
+ use_ansi_coloring: true
506
+ filesize_format: "b" # b, kb, kib, mb, mib, gb, gib, tb, tib, pb, pib, eb, eib, auto
507
+ edit_mode: emacs # vi
508
+ max_history_size: 10000
509
+ log_level: error
510
+ }
511
+ ```
512
+
513
+ if you want to go full-tilt on theming, you'll want to theme all the items I mentioned at the very beginning, including LS_COLORS, and the prompt. Good luck!
514
+
515
+ ### Working on light background terminal
516
+
517
+ Nushell's default config file contains a light theme definition, if you are working on a light background terminal, you can apply the light theme easily.
518
+
519
+ ```nu
520
+ # in $nu.config-path
521
+ $env.config = {
522
+ ...
523
+ color_config: $dark_theme # if you want a light theme, replace `$dark_theme` to `$light_theme`
524
+ ...
525
+ }
526
+ ```
527
+
528
+ You can just change it to light theme by replacing `$dark_theme` to `$light_theme`
529
+
530
+ ```nu
531
+ # in $nu.config-path
532
+ $env.config = {
533
+ ...
534
+ color_config: $light_theme # if you want a light theme, replace `$dark_theme` to `$light_theme`
535
+ ...
536
+ }
537
+ ```
538
+
539
+ ## Accessibility
540
+
541
+ It's often desired to have the minimum amount of decorations when using a screen reader. In those cases, it's possible to disable borders and other decorations for both table and errors with the following options:
542
+
543
+ ```nu
544
+ # in $nu.config-path
545
+ $env.config = {
546
+ ...
547
+ table: {
548
+ ...
549
+ mode: "none"
550
+ ...
551
+ }
552
+ error_style: "plain"
553
+ ...
554
+ }
555
+
556
+ ```
557
+
558
+ ## Line editor menus (completion, history, help…)
559
+
560
+ Reedline (Nu’s line editor) style is not using the `color_config` key.
561
+ Instead, each menu has its own style to be configured separately.
562
+ See the [section dedicated to Reedline’s menus configuration](line_editor.md#menus) to learn more on this.
coming_from_bash.md ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Coming from Bash
2
+
3
+ If you're coming from `Git Bash` on Windows, then the external commands you're used to (bash, grep, etc) will not be available in `nu` by default (unless you had explicitly made them available in the Windows Path environment variable).
4
+ To make these commands available in `nu` as well, add the following line to your `config.nu` with either `append` or `prepend`.
5
+
6
+ ```
7
+ $env.Path = ($env.Path | prepend 'C:\Program Files\Git\usr\bin')
8
+ ```
9
+
10
+ Note: this table assumes Nu 0.60.0 or later.
11
+
12
+ | Bash | Nu | Task |
13
+ | ------------------------------------ | ------------------------------------------------------------- | ----------------------------------------------------------------- |
14
+ | `ls` | `ls` | Lists the files in the current directory |
15
+ | `ls <dir>` | `ls <dir>` | Lists the files in the given directory |
16
+ | `ls pattern*` | `ls pattern*` | Lists files that match a given pattern |
17
+ | `ls -la` | `ls --long --all` or `ls -la` | List files with all available information, including hidden files |
18
+ | `ls -d */` | `ls \| where type == dir` | List directories |
19
+ | `find . -name *.rs` | `ls **/*.rs` | Find recursively all files that match a given pattern |
20
+ | `find . -name Makefile \| xargs vim` | `ls **/Makefile \| get name \| vim $in` | Pass values as command parameters |
21
+ | `cd <directory>` | `cd <directory>` | Change to the given directory |
22
+ | `cd` | `cd` | Change to the home directory |
23
+ | `cd -` | `cd -` | Change to the previous directory |
24
+ | `mkdir <path>` | `mkdir <path>` | Creates the given path |
25
+ | `mkdir -p <path>` | `mkdir <path>` | Creates the given path, creating parents as necessary |
26
+ | `touch test.txt` | `touch test.txt` | Create a file |
27
+ | `> <path>` | `\| save --raw <path>` | Save string into a file |
28
+ | `>> <path>` | `\| save --raw --append <path>` | Append string to a file |
29
+ | `> /dev/null` | `\| ignore` | Discard command output |
30
+ | `> /dev/null 2>&1` | `out+err> /dev/null` | Discard command output, including stderr |
31
+ | `command arg1 arg2 2>&1 \| less` | `run-external --redirect-combine command [arg1 arg2] \| less` | Pipe stdout+stderr of a command into less, output updated live |
32
+ | `cat <path>` | `open --raw <path>` | Display the contents of the given file |
33
+ | | `open <path>` | Read a file as structured data |
34
+ | `mv <source> <dest>` | `mv <source> <dest>` | Move file to new location |
35
+ | `cp <source> <dest>` | `cp <source> <dest>` | Copy file to new location |
36
+ | `cp -r <source> <dest>` | `cp -r <source> <dest>` | Copy directory to a new location, recursively |
37
+ | `rm <path>` | `rm <path>` | Remove the given file |
38
+ | | `rm -t <path>` | Move the given file to the system trash |
39
+ | `rm -rf <path>` | `rm -r <path>` | Recursively removes the given path |
40
+ | `date -d <date>` | `"<date>" \| into datetime -f <format>` | Parse a date ([format documentation](https://docs.rs/chrono/0.4.15/chrono/format/strftime/index.html)) |
41
+ | `sed` | `str replace` | Find and replace a pattern in a string |
42
+ | `grep <pattern>` | `where $it =~ <substring>` or `find <substring>` | Filter strings that contain the substring |
43
+ | `man <command>` | `help <command>` | Get the help for a given command |
44
+ | | `help commands` | List all available commands |
45
+ | | `help --find <string>` | Search for match in all available commands |
46
+ | `command1 && command2` | `command1; command2` | Run a command, and if it's successful run a second |
47
+ | `stat $(which git)` | `stat (which git).path` | Use command output as argument for other command |
48
+ | `echo /tmp/$RANDOM` | `$"/tmp/(random integer)"` | Use command output in a string |
49
+ | `cargo b --jobs=$(nproc)` | `cargo b $"--jobs=(sys \| get cpu \| length)"` | Use command output in an option |
50
+ | `echo $PATH` | `$env.PATH` (Non-Windows) or `$env.Path` (Windows) | See the current path |
51
+ | `<update ~/.bashrc>` | `vim $nu.config-path` | Update PATH permanently |
52
+ | `export PATH = $PATH:/usr/other/bin` | `$env.PATH = ($env.PATH \| append /usr/other/bin)` | Update PATH temporarily |
53
+ | `export` | `$env` | List the current environment variables |
54
+ | `<update ~/.bashrc>` | `vim $nu.config-path` | Update environment variables permanently |
55
+ | `FOO=BAR ./bin` | `FOO=BAR ./bin` | Update environment temporarily |
56
+ | `export FOO=BAR` | `$env.FOO = BAR` | Set environment variable for current session |
57
+ | `echo $FOO` | `$env.FOO` | Use environment variables |
58
+ | `echo ${FOO:-fallback}` | `$env.FOO? \| default "ABC"` | Use a fallback in place of an unset variable |
59
+ | `unset FOO` | `hide-env FOO` | Unset environment variable for current session |
60
+ | `alias s="git status -sb"` | `alias s = git status -sb` | Define an alias temporarily |
61
+ | `type FOO` | `which FOO` | Display information about a command (builtin, alias, or executable) |
62
+ | `<update ~/.bashrc>` | `vim $nu.config-path` | Add and edit alias permanently (for new shells) |
63
+ | `bash -c <commands>` | `nu -c <commands>` | Run a pipeline of commands |
64
+ | `bash <script file>` | `nu <script file>` | Run a script file |
65
+ | `\` | `( <command> )` | A command can span multiple lines when wrapped with `(` and `)` |
66
+ | `pwd` | `$env.PWD` | Display the current directory |
67
+ | `read var` | `let var = input` | Get input from the user. |
68
+
coming_from_cmd.md ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Coming from CMD.EXE
2
+
3
+ This table was last updated for Nu 0.67.0.
4
+
5
+ | CMD.EXE | Nu | Task |
6
+ | ------------------------------------ | ----------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
7
+ | `ASSOC` | | Displays or modifies file extension associations |
8
+ | `BREAK` | | Trigger debugger breakpoint |
9
+ | `CALL <filename.bat>` | `<filename.bat>` | Run a batch program |
10
+ | | `nu <filename>` | Run a nu script in a fresh context |
11
+ | | `source <filename>` | Run a nu script in this context |
12
+ | | `use <filename>` | Run a nu script as a module |
13
+ | `CD` or `CHDIR` | `$env.PWD` | Get the present working directory |
14
+ | `CD <directory>` | `cd <directory>` | Change the current directory |
15
+ | `CD /D <drive:directory>` | `cd <drive:directory>` | Change the current directory |
16
+ | `CLS` | `clear` | Clear the screen |
17
+ | `COLOR` | | Set the console default foreground/background colors |
18
+ | | `ansi {flags} (code)` | Output ANSI codes to change color |
19
+ | `COPY <source> <destination>` | `cp <source> <destination>` | Copy files |
20
+ | `COPY <file1>+<file2> <destination>` | `[<file1>, <file2>] \| each { open --raw } \| str join \| save --raw <destination>` | Append multiple files into one |
21
+ | `DATE /T` | `date now` | Get the current date |
22
+ | `DATE` | | Set the date |
23
+ | `DEL <file>` or `ERASE <file>` | `rm <file>` | Delete files |
24
+ | `DIR` | `ls` | List files in the current directory |
25
+ | `ECHO <message>` | `print <message>` | Print the given values to stdout |
26
+ | `ECHO ON` | | Echo executed commands to stdout |
27
+ | `ENDLOCAL` | `export-env` | Change env in the caller |
28
+ | `EXIT` | `exit` | Close the prompt or script |
29
+ | `FOR %<var> IN (<set>) DO <command>` | `for $<var> in <set> { <command> }` | Run a command for each item in a set |
30
+ | `FTYPE` | | Displays or modifies file types used in file extension associations |
31
+ | `GOTO` | | Jump to a label |
32
+ | `IF ERRORLEVEL <number> <command>` | `if $env.LAST_EXIT_CODE >= <number> { <command> }` | Run a command if the last command returned an error code >= specified |
33
+ | `IF <string> EQU <string> <command>` | `if <string> == <string> { <command> }` | Run a command if strings match |
34
+ | `IF EXIST <filename> <command>` | | Run a command if the file exists |
35
+ | `IF DEFINED <variable> <command>` | | Run a command if the variable is defined |
36
+ | `MD` or `MKDIR` | `mkdir` | Create directories |
37
+ | `MKLINK` | | Create symbolic links |
38
+ | `MOVE` | `mv` | Move files |
39
+ | `PATH` | `$env.Path` | Display the current path variable |
40
+ | `PATH <path>;%PATH%` | `$env.Path = ($env.Path \| prepend <path>`) | Edit the path variable |
41
+ | `PATH %PATH%;<path>` | `$env.Path = ($env.Path \| prepend <path>`) | Edit the path variable |
42
+ | `PAUSE` | `input "Press any key to continue . . ."` | Pause script execution |
43
+ | `PROMPT <template>` | `$env.PROMPT_COMMAND = { <command> }` | Change the terminal prompt |
44
+ | `PUSHD <path>`/`POPD` | `enter <path>`/`exit` | Change working directory temporarily |
45
+ | `REM` | `#` | Comments |
46
+ | `REN` or `RENAME` | `mv` | Rename files |
47
+ | `RD` or `RMDIR` | `rm` | Remove directory |
48
+ | `SET <var>=<string>` | `$env.<var> = <string>` | Set environment variables |
49
+ | `SETLOCAL` | (default behavior) | Localize environment changes to a script |
50
+ | `START <path>` | `explorer <path>` | Open a file as if double-clicked in File Explorer |
51
+ | `TIME /T` | `date now \| format date "%H:%M:%S"` | Get the current time |
52
+ | `TIME` | | Set the current time |
53
+ | `TITLE` | | Set the cmd.exe window name |
54
+ | `TYPE` | `open --raw` | Display the contents of a text file |
55
+ | | `open` | Open a file as structured data |
56
+ | `VER` | | Display the OS version |
57
+ | `VERIFY` | | Verify that file writes happen |
58
+ | `VOL` | | Show drive information |
59
+
60
+ Before Nu version 0.67, Nu [used to](https://www.nushell.sh/blog/2022-08-16-nushell-0_67.html#windows-cmd-exe-changes-rgwood) use CMD.EXE to launch external commands, which meant that the above builtins could be run as an `^external` command. As of version 0.67, however, Nu no longer uses CMD.EXE to launch externals, meaning the above builtins cannot be run from within Nu, except for `ASSOC`, `CLS`, `ECHO`, `FTYPE`, `MKLINK`, `PAUSE`, `START`, `VER`, and `VOL`, which are explicitly allowed to be interpreted by CMD if no executable by that name exists.
coming_to_nu.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Coming to Nu
2
+
3
+ If you are familiar with other shells or programming languages, you might find this chapter useful to get up to speed.
4
+
5
+ [Coming from Bash](coming_from_bash.md) shows how some patterns typical for Bash, or POSIX shells in general, can be mapped to Nushell.
6
+ Similarly, [Coming from CMD.EXE](coming_from_cmd.md) shows how built-in commands in the Windows Command Prompt can be mapped to Nushell.
7
+
8
+ Similar comparisons are made for some [other shells and domain-specific languages](nushell_map.md), [imperative languages](nushell_map_imperative.md), and [functional languages](nushell_map_functional.md).
9
+ A separate comparison is made specifically for [operators](nushell_operator_map.md).
command_signature.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Command signature
2
+
3
+ nu commands can be given explicit signatures; take [`str stats`](/commands/docs/str_stats.md) as an example, the signature is like this:
4
+
5
+ ```nu
6
+ def "str stats" []: string -> record { }
7
+ ```
8
+
9
+ The type names between the `:` and the opening curly brace `{` describe the command's input/output pipeline types. The input type for a given pipeline, in this case `string`, is given before the `->`; and the output type `record` is given after `->`. There can be multiple input/output types. If there are multiple input/output types, they can be placed within brackets and separated with commas, as in [`str join`](/commands/docs/str_join.md):
10
+
11
+ ```nu
12
+ def "str join" [separator?: string]: [list -> string, string -> string] { }
13
+ ```
14
+
15
+ It says that the [`str join`](/commands/docs/str_join.md) command takes an optional `string` type argument, and an input pipeline of either a `list` (implying `list<any>`) with output type of `string`, or a single `string`, again with output type of `string`.
16
+
17
+ Some commands don't accept or require data through the input pipeline, thus the input type will be `<nothing>`.
18
+ The same is true for the output type if the command returns `null` (e.g. [`rm`](/commands/docs/rm.md) or [`hide`](/commands/docs/hide.md)):
19
+
20
+ ```nu
21
+ def hide [module: string, members?]: nothing -> nothing { }
22
+ ```
configuration.md ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configuration
2
+
3
+ ## Nushell Configuration with `env.nu` and `config.nu`
4
+
5
+ Nushell uses a configuration system that loads and runs two Nushell script files at launch time:
6
+
7
+ - `env.nu` is used to define environment variables. These typically get used in the second config file, config.nu.
8
+ - `config.nu` is used to add definitions, aliases, and more to the global namespace. It can use the environment variables defined in `env.nu`, which is why there's two separate files.
9
+
10
+ You can check where Nushell is reading these config files from by calling `$nu.env-path` and `$nu.config-path`.
11
+
12
+ ```nu
13
+ > $nu.env-path
14
+ /Users/FirstNameLastName/Library/Application Support/nushell/env.nu
15
+ ```
16
+
17
+ _(You can think of the Nushell config loading sequence as executing two [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) lines on startup: `source /path/to/env.nu` and `source /path/to/config.nu`. Therefore, using `env.nu` for environment and `config.nu` for other config is just a convention.)_
18
+
19
+ When you launch Nushell without these files set up, Nushell will prompt you to download the [`default env.nu`](https://github.com/nushell/nushell/blob/main/crates/nu-utils/src/sample_config/default_env.nu) and [`default config.nu`](https://github.com/nushell/nushell/blob/main/crates/nu-utils/src/sample_config/default_config.nu).
20
+
21
+ You can browse the default files for default values of environment variables and a list of all configurable settings.
22
+
23
+ ### Configuring `$env.config`
24
+
25
+ Nushell's main settings are kept in the `config` environment variable as a record. This record can be created using:
26
+
27
+ ```nu
28
+ $env.config = {
29
+ ...
30
+ }
31
+ ```
32
+
33
+ You can also shadow `$env.config` and update it:
34
+
35
+ ```nu
36
+ $env.config = ($env.config | upsert <field name> <field value>)
37
+ ```
38
+
39
+ By convention, this variable is defined in the `config.nu` file.
40
+
41
+ ### Environment
42
+
43
+ You can set environment variables for the duration of a Nushell session using the `$env.<var> = <val>` structure inside the `env.nu` file. For example:
44
+
45
+ ```nu
46
+ $env.FOO = 'BAR'
47
+ ```
48
+
49
+ _(Although $env.config is an environment variable, it is still defined by convention inside config.nu.)_
50
+
51
+ These are some important variables to look at for Nushell-specific settings:
52
+
53
+ - `LS_COLORS`: Sets up colors per file type in ls
54
+ - `PROMPT_COMMAND`: Code to execute for setting up the prompt (block or string)
55
+ - `PROMPT_COMMAND_RIGHT`: Code to execute for setting up the right prompt (block)
56
+ - `PROMPT_INDICATOR = "〉"`: The indicator printed after the prompt (by default ">"-like Unicode symbol)
57
+ - `PROMPT_INDICATOR_VI_INSERT = ": "`
58
+ - `PROMPT_INDICATOR_VI_NORMAL = "〉 "`
59
+ - `PROMPT_MULTILINE_INDICATOR = "::: "`
60
+
61
+ ### Configurations with built-in commands
62
+
63
+ Starting with release v0.64 of Nushell, we have introduced two new commands([`config nu`](/commands/docs/config_nu.md) and [`config env`](/commands/docs/config_env.md)) which help you quickly edit nu configurations with your preferred text editor/IDE
64
+
65
+ Nushell follows underneath orders to locate the editor:
66
+
67
+ 1. `$config.buffer_editor`
68
+ 2. `$env.EDITOR`
69
+ 3. `$env.VISUAL`
70
+
71
+ Note: Previous versions of Nushell were launching `notepad` on windows, otherwise `nano` when these variables weren't found. We removed defaulting to `notepad` on Windows since `notepad` is now distributed via the Windows Store and there will be a possibility of not having `notepad` at all.
72
+
73
+ ### Color Config section
74
+
75
+ You can learn more about setting up colors and theming in the [associated chapter](coloring_and_theming.md).
76
+
77
+ ## Remove Welcome Message
78
+
79
+ To remove the welcome message, you need to edit your `config.nu` by typing `config nu` in your terminal, then you go to the global configuration `$env.config` and set `show_banner` option to false, like this:
80
+
81
+ @[code](@snippets/installation/remove_welcome_message.nu)
82
+
83
+ ## Configuring Nu as a login shell
84
+
85
+ To use Nu as a login shell, you'll need to configure the `$env` variable. This sets up the environment for external programs.
86
+
87
+ To get an idea of which environment variables are set up by your current login shell, start a new shell session, then run nu in that shell.
88
+
89
+ You can then configure some `$env.<var> = <val>` that setup the same environment variables in your nu login shell. Use this command to generate some `$env.<var> = <val>` for all the environment variables:
90
+
91
+ ```nu
92
+ $env | reject config | transpose key val | each {|r| echo $"$env.($r.key) = '($r.val)'"} | str join (char nl)
93
+ ```
94
+
95
+ This will print out `$env.<var> = <val>` lines, one for each environment variable along with its setting. You may not need all of them, for instance the `PS1` variable is bash specific.
96
+
97
+ Next, on some distros you'll also need to ensure Nu is in the /etc/shells list:
98
+
99
+ ```sh
100
+ > cat /etc/shells
101
+ # /etc/shells: valid login shells
102
+ /bin/sh
103
+ /bin/dash
104
+ /bin/bash
105
+ /bin/rbash
106
+ /usr/bin/screen
107
+ /usr/bin/fish
108
+ /home/jonathan/.cargo/bin/nu
109
+ ```
110
+
111
+ With this, you should be able to `chsh` and set Nu to be your login shell. After a logout, on your next login you should be greeted with a shiny Nu prompt.
112
+
113
+ ### Configuration with `login.nu`
114
+
115
+ If Nushell is used as a login shell, you can use a specific configuration file which is only sourced in this case. Therefore a file with name `login.nu` has to be in the standard configuration directory.
116
+
117
+ The file `login.nu` is sourced after `env.nu` and `config.nu`, so that you can overwrite those configurations if you need.
118
+
119
+ There is an environment variable `$nu.loginshell-path` containing the path to this file.
120
+
121
+ ### macOS: Keeping `/usr/bin/open` as `open`
122
+
123
+ Some tools (e.g. Emacs) rely on an [`open`](/commands/docs/open.md) command to open files on Mac.
124
+ As Nushell has its own [`open`](/commands/docs/open.md) command which has different semantics and shadows `/usr/bin/open`, these tools will error out when trying to use it.
125
+ One way to work around this is to define a custom command for Nushell's [`open`](/commands/docs/open.md) and create an alias for the system's [`open`](/commands/docs/open.md) in your `config.nu` file like this:
126
+
127
+ ```nu
128
+ def nuopen [arg, --raw (-r)] { if $raw { open -r $arg } else { open $arg } }
129
+ alias open = ^open
130
+ ```
131
+
132
+ The `^` symbol _escapes_ the Nushell `open` command, which invokes the operating system's `open` command.
133
+ For more about escape and `^` see the [chapter about escapes](escaping.md).
134
+
135
+ ## PATH configuration
136
+
137
+ In Nushell, [the PATH environment variable](<https://en.wikipedia.org/wiki/PATH_(variable)>) (Path on Windows) is a list of paths. To append a new path to it, you can use `$env.<var> = <val>` and [`append`](/commands/docs/append.md) in `env.nu`:
138
+
139
+ ```nu
140
+ $env.PATH = ($env.PATH | split row (char esep) | append '/some/path')
141
+ ```
142
+
143
+ This will append `/some/path` to the end of PATH; you can also use [`prepend`](/commands/docs/prepend.md) to add entries to the start of PATH.
144
+
145
+ Note the `split row (char esep)` step. We need to add it because in `env.nu`, the environment variables inherited from the host process are still strings. The conversion step of environment variables to Nushell values happens after reading the config files (see also the [Environment](environment.html#environment-variable-conversions) section). After that, for example in the Nushell REPL when `PATH`/`Path` is a list , you can use [`append`](/commands/docs/append.md)/[`prepend`](/commands/docs/prepend.md) directly.
146
+
147
+ To prepend a new path only if not already listed, one can add to `env.nu`:
148
+ ```nu
149
+ # create a new string holding the desired path
150
+ let my_path = ( $nu.home-path | path join "bin" )
151
+ # return $env.PATH if $my_path is already listed, return $env.PATH with $my_path prepended otherwise
152
+ $env.PATH = ( if $my_path in $env.PATH { $env.PATH } else { $env.PATH | prepend $my_path } )
153
+ ```
154
+
155
+ ### Homebrew
156
+
157
+ [Homebrew](https://brew.sh/) is a popular package manager that often requires PATH configuration. To add it to your Nushell PATH:
158
+
159
+ ```nu
160
+ # macOS ARM64 (Apple Silicon)
161
+ $env.PATH = ($env.PATH | split row (char esep) | prepend '/opt/homebrew/bin')
162
+
163
+ # Linux
164
+ $env.PATH = ($env.PATH | split row (char esep) | prepend '/home/linuxbrew/.linuxbrew/bin')
165
+ ```
control_flow.md ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Control Flow
2
+
3
+ Nushell provides several commands that help determine how different groups of code are executed. In programming languages this functionality is often referred to as _control flow_.
4
+
5
+ ::: tip
6
+ One thing to note is that all of the commands discussed on this page use [blocks](/book/types_of_data.html#blocks). This means you can mutate [environmental variables](/book/environment.html) and other [mutable variables](http://localhost:8080/book/variables_and_subexpressions.html#mutable-variables) in them.
7
+ :::
8
+
9
+ ## Already covered
10
+
11
+ Below we cover some commands related to control flow, but before we get to them, it's worthwhile to note there are several pieces of functionality and concepts that have already been covered in other sections that are also related to control flow or that can be used in the same situations. These include:
12
+
13
+ - Pipes on the [pipelines](/book/pipelines.html) page.
14
+ - Closures on the [types of data](/book/types_of_data.html) page.
15
+ - Iteration commands on the [working with lists](/book/working_with_lists.html) page. Such as:
16
+ - [`each`](/commands/docs/each.html)
17
+ - [`where`](/commands/docs/where.html)
18
+ - [`reduce`](/commands/docs/reduce.html)
19
+
20
+ ## Choice (Conditionals)
21
+
22
+ The following commands execute code based on some given condition.
23
+
24
+ ::: tip
25
+ The choice/conditional commands are expressions so they return values, unlike the other commands on this page. This means the following works.
26
+
27
+ ```nu
28
+ > 'foo' | if $in == 'foo' { 1 } else { 0 } | $in + 2
29
+ 3
30
+ ```
31
+
32
+ :::
33
+
34
+ ### `if`
35
+
36
+ [`if`](/commands/docs/if.html) evaluates branching [blocks](/book/types_of_data.html#blocks) of code based on the results of one or more conditions similar to the "if" functionality in other programming languages. For example:
37
+
38
+ ```nu
39
+ > if $x > 0 { 'positive' }
40
+ ```
41
+
42
+ Returns `'positive`' when the condition is `true` (`$x` is greater than zero) and `null` when the condition is `false` (`$x` is less than or equal to zero).
43
+
44
+ We can add an `else` branch to the `if` after the first block which executes and returns the resulting value from the `else` block when the condition is `false`. For example:
45
+
46
+ ```nu
47
+ > if $x > 0 { 'positive' } else { 'non-positive' }
48
+ ```
49
+
50
+ This time it returns `'positive'` when the condition is `true` (`$x` is greater than zero) and `'non-positive`' when the condition is `false` (`$x` is less than or equal to zero).
51
+
52
+ We can also chain multiple `if`s together like the following:
53
+
54
+ ```nu
55
+ > if $x > 0 { 'positive' } else if $x == 0 { 'zero' } else { "negative" }
56
+ ```
57
+
58
+ When the first condition is `true` (`$x` is greater than zero) it will return `'positive'`, when the first condition is `false` and the next condition is `true` (`$x` equals zero) it will return `'zero'`, otherwise it will return `'negative'` (when `$x` is less than zero).
59
+
60
+ ### `match`
61
+
62
+ [`match`](/commands/docs/match.html) executes one of several conditional branches based on the value given to match. You can also do some [pattern matching](/cookbook/pattern_matching.html) to unpack values in composite types like lists and records.
63
+
64
+ Basic usage of [`match`](/commands/docs/match.html) can conditionally run different code like a "switch" statement common in other languages. [`match`](/commands/docs/match.html) checks if the value after the word [`match`](/commands/docs/match.html) is equal to the value at the start of each branch before the `=>` and if it does, it executes the code after that branch's `=>`.
65
+
66
+ ```nu
67
+ > match 3 {
68
+ 1 => 'one',
69
+ 2 => {
70
+ let w = 'w'
71
+ 't' + $w + 'o'
72
+ },
73
+ 3 => 'three',
74
+ 4 => 'four'
75
+ }
76
+ three
77
+ ```
78
+
79
+ The branches can either return a single value or, as shown in the second branch, can return the results of a [block](/book/types_of_data.html#blocks).
80
+
81
+ #### Catch all branch
82
+
83
+ You can have also have a catch all condition for if the given value doesn't match any of the other conditions by having a branch whose matching value is `_`.
84
+
85
+ ```nu
86
+ > let foo = match 7 {
87
+ 1 => 'one',
88
+ 2 => 'two',
89
+ 3 => 'three',
90
+ _ => 'other number'
91
+ }
92
+ > $foo
93
+ other number
94
+ ```
95
+
96
+ (Reminder, [`match`](/commands/docs/match.html) is an expression which is why we can assign the result to `$foo` here).
97
+
98
+ #### Pattern Matching
99
+
100
+ You can "unpack" values from types like lists and records with [pattern matching](/cookbook/pattern_matching.html). You can then assign variables to the parts you want to unpack and use them in the matched expressions.
101
+
102
+ ```nu
103
+ > let foo = { name: 'bar', count: 7 }
104
+ > match $foo {
105
+ { name: 'bar', count: $it } => ($it + 3),
106
+ { name: _, count: $it } => ($it + 7),
107
+ _ => 1
108
+ }
109
+ 10
110
+ ```
111
+
112
+ The `_` in the second branch means it matches any record with field `name` and `count`, not just ones where `name` is `'bar'`.
113
+
114
+ #### Guards
115
+
116
+ You can also add an additional condition to each branch called a "guard" to determine if the branch should be matched. To do so, after the matched pattern put `if` and then the condition before the `=>`.
117
+
118
+ ```nu
119
+ > let foo = { name: 'bar', count: 7 }
120
+ > match $foo {
121
+ { name: 'bar', count: $it } if $it < 5 => ($it + 3),
122
+ { name: 'bar', count: $it } if $it >= 5 => ($it + 7),
123
+ _ => 1
124
+ }
125
+ 14
126
+ ```
127
+
128
+ ---
129
+
130
+ You can find more details about [`match`](/commands/docs/match.html) in the [pattern matching cookbook page](https://www.nushell.sh/cookbook/pattern_matching.html).
131
+
132
+ ## Loops
133
+
134
+ The loop commands allow you to repeat a block of code multiple times.
135
+
136
+ ### Loops and other iterating commands
137
+
138
+ The functionality of the loop commands is similar to commands that apply a closure over elements in a list or table like [`each`](/commands/docs/each.html) or [`where`](/commands/docs/where.html) and many times you can accomplish the same thing with either. For example:
139
+
140
+ ```nu
141
+ > mut result = []
142
+ > for $it in [1 2 3] { $result = ($result | append ($it + 1)) }
143
+ > $result
144
+ ╭───┬───╮
145
+ │ 0 │ 2 │
146
+ │ 1 │ 3 │
147
+ │ 2 │ 4 │
148
+ ╰───┴───╯
149
+
150
+
151
+ > [1 2 3] | each { $in + 1 }
152
+ ╭───┬───╮
153
+ │ 0 │ 2 │
154
+ │ 1 │ 3 │
155
+ │ 2 │ 4 │
156
+ ╰───┴───╯
157
+ ```
158
+
159
+ While it may be tempting to use loops if you're familiar with them in other languages, it is considered more in the [Nushell-style](book/thinking_in_nu.html) (idiomatic) to use commands that apply closures when you can solve a problem either way. The reason for this is because of a pretty big downside with using loops.
160
+
161
+ #### Loop disadvantages
162
+
163
+ The biggest downside of loops is that they are statements, unlike [`each`](/commands/docs/each.html) which is an expression. Expressions, like [`each`](/commands/docs/each.html) always result in some output value, however statements do not.
164
+
165
+ This means that they don't work well with immutable variables and using immutable variables is considered a more [Nushell-style](/book/thinking_in_nu.html#variables-are-immutable). Without a mutable variable declared beforehand in the example in the previous section, it would be impossible to use [`for`](/commands/docs/each.html) to get the list of numbers with incremented numbers, or any value at all.
166
+
167
+ Statements also don't work in Nushell pipelines which require some output. In fact Nushell will give an error if you try:
168
+
169
+ ```nu
170
+ > [1 2 3] | for x in $in { $x + 1 } | $in ++ [5 6 7]
171
+ Error: nu::parser::unexpected_keyword
172
+
173
+ × Statement used in pipeline.
174
+ ╭─[entry #5:1:1]
175
+ 1 │ [1 2 3] | for x in $in { $x + 1 } | $in ++ [5 6 7]
176
+ · ─┬─
177
+ · ╰── not allowed in pipeline
178
+ ╰────
179
+ help: 'for' keyword is not allowed in pipeline. Use 'for' by itself, outside of a pipeline.
180
+ ```
181
+
182
+ Because Nushell is very pipeline oriented, this means using expression commands like [`each`](/commands/docs/each.html) is typically more natural than loop statements.
183
+
184
+ #### Loop advantages
185
+
186
+ If loops have such a big disadvantage, why do they exist? Well, one reason is that closures, like [`each`](/commands/docs/each.html) uses, can't modify mutable variables in the surrounding environment. If you try to modify a mutable variable in a closure you will get an error:
187
+
188
+ ```nu
189
+ > mut foo = []
190
+ > [1 2 3] | each { $foo = ($foo | append ($in + 1)) }
191
+ Error: nu::parser::expected_keyword
192
+
193
+ × Capture of mutable variable.
194
+ ╭─[entry #8:1:1]
195
+ 1 │ [1 2 3] | each { $foo = ($foo | append ($in + 1)) }
196
+ · ──┬─
197
+ · ╰── capture of mutable variable
198
+ ╰────
199
+ ```
200
+
201
+ If you modify an environmental variable in a closure, you can, but it will only modify it within the scope of the closure, leaving it unchanged everywhere else. Loops, however, use [blocks](/book/types_of_data.html#blocks) which means they can modify a regular mutable variable or an environmental variable within the larger scope.
202
+
203
+ ```nu
204
+ > mut result = []
205
+ > for $it in [1 2 3] { $result = ($result | append ($it + 1)) }
206
+ > $result
207
+ ╭───┬───╮
208
+ │ 0 │ 2 │
209
+ │ 1 │ 3 │
210
+ │ 2 │ 4 │
211
+ ╰───┴───╯
212
+ ```
213
+
214
+ ### `for`
215
+
216
+ [`for`](/commands/docs/for.html) loops over a range or collection like a list or a table.
217
+
218
+ ```nu
219
+ > for x in [1 2 3] { $x * $x | print }
220
+ 1
221
+ 4
222
+ 9
223
+ ```
224
+
225
+ #### Expression command alternatives
226
+
227
+ - [`each`](/commands/docs/each.html)
228
+ - [`par-each`](/commands/docs/par-each.html)
229
+ - [`where`](/commands/docs/where.html)/[`filter`](/commands/docs/filter.html)
230
+ - [`reduce`](/commands/docs/reduce.html)
231
+
232
+ ### `while`
233
+
234
+ [`while`](/commands/docs/while.html) loops the same block of code until the given condition is `false`.
235
+
236
+ ```nu
237
+ > mut x = 0; while $x < 10 { $x = $x + 1 }; $x
238
+ 10
239
+ ```
240
+
241
+ #### Expression command alternatives
242
+
243
+ The "until" and other "while" commands
244
+
245
+ - [`take until`](/commands/docs/take_until.html)
246
+ - [`take while`](/commands/docs/take_while.html)
247
+ - [`skip until`](/commands/docs/skip_until.html)
248
+ - [`skip while`](/commands/docs/skip_while.html)
249
+
250
+ ### `loop`
251
+
252
+ [`loop`](/commands/docs/loop.html) loops a block infinitely. You can use [`break`](/commands/docs/break.html) (as described in the next section) to limit how many times it loops. It can also be handy for continuously running scripts, like an interactive prompt.
253
+
254
+ ```nu
255
+ > mut x = 0; loop { if $x > 10 { break }; $x = $x + 1 }; $x
256
+ 11
257
+ ```
258
+
259
+ ### `break`
260
+
261
+ [`break`](/commands/docs/break.html) will stop executing the code in a loop and resume execution after the loop. Effectively "break"ing out of the loop.
262
+
263
+ ```nu
264
+ > for x in 1..10 { if $x > 3 { break }; print $x }
265
+ 1
266
+ 2
267
+ 3
268
+ ```
269
+
270
+ ### `continue`
271
+
272
+ [`continue`](/commands/docs/continue.html) will stop execution of the current loop, skipping the rest of the code in the loop, and will go to the next loop. If the loop would normally end, like if [`for`](/commands/docs/for.html) has iterated through all the given elements, or if [`while`](/commands/docs/while.html)'s condition is now false, it won't loop again and execution will continue after the loop block.
273
+
274
+ ```nu
275
+ > mut x = -1; while $x <= 6 { $x = $x + 1; if $x mod 3 == 0 { continue }; print $x }
276
+ 1
277
+ 2
278
+ 4
279
+ 5
280
+ 7
281
+ ```
282
+
283
+ ## Errors
284
+
285
+ ### `error make`
286
+
287
+ [`error make`](/commands/docs/error_make.html) creates an error that stops execution of the code and any code that called it, until either it is handled by a [`try`](/commands/docs/try.html) block, or it ends the script and outputs the error message. This functionality is the same as "exceptions" in other languages.
288
+
289
+ ```nu
290
+ > print 'printed'; error make { msg: 'Some error info' }; print 'unprinted'
291
+ printed
292
+ Error: × Some error info
293
+ ╭─[entry #9:1:1]
294
+ 1 │ print 'printed'; error make { msg: 'Some error info' }; print 'unprinted'
295
+ · ─────┬────
296
+ · ╰── originates from here
297
+ ╰────
298
+ ```
299
+
300
+ The record passed to it provides some information to the code that catches it or the resulting error message.
301
+
302
+ You can find more information about [`error make`](/commands/docs/error_make.html) and error concepts on the [Creating your own errors page](/book/creating_errors.html).
303
+
304
+ ### `try`
305
+
306
+ [`try`](/commands/docs/try.html) will catch errors created anywhere in the [`try`](/commands/docs/try.html)'s code block and resume execution of the code after the block.
307
+
308
+ ```nu
309
+ > try { error make { msg: 'Some error info' }}; print 'Resuming'
310
+ Resuming
311
+ ```
312
+
313
+ This includes catching built in errors.
314
+
315
+ ```nu
316
+ > try { 1 / 0 }; print 'Resuming'
317
+ Resuming
318
+ ```
319
+
320
+ The resulting value will be `nothing` if an error occurs and the returned value of the block if an error did not occur.
321
+
322
+ If you include a `catch` block after the [`try`](/commands/docs/try.html) block, it will execute the code in the `catch` block if an error occurred in the [`try`](/commands/docs/try.html) block.
323
+
324
+ ```nu
325
+ > try { 1 / 0 } catch { 'An error happened!' } | $in ++ ' And now I am resuming.'
326
+ An error happened! And now I am resuming.
327
+ ```
328
+
329
+ It will not execute the `catch` block if an error did not occur.
330
+
331
+ ## Other
332
+
333
+ ### `return`
334
+
335
+ [`return`](/commands/docs/return.html) Ends a closure or command early where it is called, without running the rest of the command/closure, and returns the given value. Not often necessary since the last value in a closure or command is also returned, but it can sometimes be convenient.
336
+
337
+ ```nu
338
+ def 'positive-check' [it] {
339
+ if $it > 0 {
340
+ return 'positive'
341
+ };
342
+
343
+ 'non-positive'
344
+ }
345
+ ```
346
+
347
+ ```nu
348
+ > positive-check 3
349
+ positive
350
+
351
+ > positive-check (-3)
352
+ non-positive
353
+
354
+ > let positive_check = {|it| if $it > 0 { return 'positive' }; 'non-positive' }
355
+
356
+ > do $positive_check 3
357
+ positive
358
+
359
+ > do $positive_check (-3)
360
+ non-positive
361
+ ```
creating_errors.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Creating your own errors
2
+
3
+ Using the [metadata](metadata.md) information, you can create your own custom error messages. Error messages are built of multiple parts:
4
+
5
+ - The title of the error
6
+ - The label of error message, which includes both the text of the label and the span to underline
7
+
8
+ You can use the [`error make`](/commands/docs/error_make.md) command to create your own error messages. For example, let's say you had your own command called `my-command` and you wanted to give an error back to the caller about something wrong with a parameter that was passed in.
9
+
10
+ First, you can take the span of where the argument is coming from:
11
+
12
+ ```nu
13
+ let span = (metadata $x).span;
14
+ ```
15
+
16
+ Next, you can create an error using the [`error make`](/commands/docs/error_make.md) command. This command takes in a record that describes the error to create:
17
+
18
+ ```nu
19
+ error make {msg: "this is fishy", label: {text: "fish right here", span: $span } }
20
+ ```
21
+
22
+ Together with your custom command, it might look like this:
23
+
24
+ ```nu
25
+ def my-command [x] {
26
+ let span = (metadata $x).span;
27
+ error make {
28
+ msg: "this is fishy",
29
+ label: {
30
+ text: "fish right here",
31
+ span: (metadata $x).span
32
+ }
33
+ }
34
+ }
35
+ ```
36
+
37
+ When called with a value, we'll now see an error message returned:
38
+
39
+ ```nu
40
+ > my-command 100
41
+
42
+ Error:
43
+ × this is fishy
44
+ ╭─[entry #5:1:1]
45
+ 1 │ my-command 100
46
+ · ─┬─
47
+ · ╰── fish right here
48
+ ╰────
49
+ ```
custom_commands.md ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Custom commands
2
+
3
+ Nu's ability to compose long pipelines allows you a lot of control over your data and system, but it comes at the price of a lot of typing. Ideally, you'd be able to save your well-crafted pipelines to use again and again.
4
+
5
+ This is where custom commands come in.
6
+
7
+ An example definition of a custom command:
8
+
9
+ ```nu
10
+ def greet [name] {
11
+ ['hello' $name]
12
+ }
13
+ ```
14
+
15
+ ::: tip
16
+ The value produced by the last line of a command becomes the command's returned value. In this case, a list containing the string `'hello'` and `$name` is returned. To prevent this, you can place `null` (or the [`ignore`](/commands/docs/ignore.md) command) at the end of the pipeline, like so: `['hello' $name] | null`. Also note that most file system commands, such as [`save`](/commands/docs/save.md) or [`cd`](/commands/docs/cd.md), always output `null`.
17
+ :::
18
+
19
+ In this definition, we define the `greet` command, which takes a single parameter `name`. Following this parameter is the block that represents what will happen when the custom command runs. When called, the custom command will set the value passed for `name` as the `$name` variable, which will be available to the block.
20
+
21
+ To run the above, we can call it like we would call built-in commands:
22
+
23
+ ```nu
24
+ > greet "world"
25
+ ```
26
+
27
+ As we do, we also get output just as we would with built-in commands:
28
+
29
+ ```
30
+ ───┬───────
31
+ 0 │ hello
32
+ 1 │ world
33
+ ───┴───────
34
+ ```
35
+
36
+ ::: tip
37
+ If you want to generate a single string, you can use the string interpolation syntax to embed $name in it:
38
+
39
+ ```nu
40
+ def greet [name] {
41
+ $"hello ($name)"
42
+ }
43
+
44
+ greet nushell
45
+ ```
46
+
47
+ returns `hello nushell`
48
+ :::
49
+
50
+ ## Command names
51
+
52
+ In Nushell, a command name is a string of characters. Here are some examples of valid command names: `greet`, `get-size`, `mycommand123`, `my command`, and `😊`.
53
+
54
+ _Note: It's common practice in Nushell to separate the words of the command with `-` for better readability._ For example `get-size` instead of `getsize` or `get_size`.
55
+
56
+ ## Sub-commands
57
+
58
+ You can also define subcommands to commands using a space. For example, if we wanted to add a new subcommand to [`str`](/commands/docs/str.md), we can create it by naming our subcommand to start with "str ". For example:
59
+
60
+ ```nu
61
+ def "str mycommand" [] {
62
+ "hello"
63
+ }
64
+ ```
65
+
66
+ Now we can call our custom command as if it were a built-in subcommand of [`str`](/commands/docs/str.md):
67
+
68
+ ```nu
69
+ > str mycommand
70
+ ```
71
+
72
+ Of course, commands with spaces in their names are defined in the same way:
73
+
74
+ ```nu
75
+ def "custom command" [] {
76
+ "this is a custom command with a space in the name!"
77
+ }
78
+ ```
79
+
80
+ ## Parameter types
81
+
82
+ When defining custom commands, you can name and optionally set the type for each parameter. For example, you can write the above as:
83
+
84
+ ```nu
85
+ def greet [name: string] {
86
+ $"hello ($name)"
87
+ }
88
+ ```
89
+
90
+ The types of parameters are optional. Nushell supports leaving them off and treating the parameter as `any` if so. If you annotated a type on a parameter, Nushell will check this type when you call the function.
91
+
92
+ For example, let's say you wanted to take in an `int` instead:
93
+
94
+ ```nu
95
+ def greet [name: int] {
96
+ $"hello ($name)"
97
+ }
98
+
99
+ greet world
100
+ ```
101
+
102
+ If we try to run the above, Nushell will tell us that the types don't match:
103
+
104
+ ```
105
+ error: Type Error
106
+ ┌─ shell:6:7
107
+
108
+ 5 │ greet world
109
+ │ ^^^^^ Expected int
110
+ ```
111
+
112
+ This can help you guide users of your definitions to call them with only the supported types.
113
+
114
+ The currently accepted types are (as of version 0.86.0):
115
+
116
+ - `any`
117
+ - `binary`
118
+ - `bool`
119
+ - `cell-path`
120
+ - `closure`
121
+ - `datetime`
122
+ - `directory`
123
+ - `duration`
124
+ - `error`
125
+ - `filesize`
126
+ - `float`
127
+ - `glob`
128
+ - `int`
129
+ - `list`
130
+ - `nothing`
131
+ - `number`
132
+ - `path`
133
+ - `range`
134
+ - `record`
135
+ - `string`
136
+ - `table`
137
+
138
+ ## Parameters with a default value
139
+
140
+ To make a parameter optional and directly provide a default value for it you can provide a default value in the command definition.
141
+
142
+ ```nu
143
+ def greet [name = "nushell"] {
144
+ $"hello ($name)"
145
+ }
146
+ ```
147
+
148
+ You can call this command either without the parameter or with a value to override the default value:
149
+
150
+ ```nu
151
+ > greet
152
+ hello nushell
153
+ > greet world
154
+ hello world
155
+ ```
156
+
157
+ You can also combine a default value with a [type requirement](#parameter-types):
158
+
159
+ ```nu
160
+ def congratulate [age: int = 18] {
161
+ $"Happy birthday! You are ($age) years old now!"
162
+ }
163
+ ```
164
+
165
+ If you want to check if an optional parameter is present or not and not just rely on a default value use [optional positional parameters](#optional-positional-parameters) instead.
166
+
167
+ ## Optional positional parameters
168
+
169
+ By default, positional parameters are required. If a positional parameter is not passed, we will encounter an error:
170
+
171
+ ```nu
172
+ × Missing required positional argument.
173
+ ╭─[entry #23:1:1]
174
+ 1 │ greet
175
+ · ▲
176
+ · ╰── missing name
177
+ ╰────
178
+ help: Usage: greet <name>
179
+ ```
180
+
181
+ We can instead mark a positional parameter as optional by putting a question mark (`?`) after its name. For example:
182
+
183
+ ```nu
184
+ def greet [name?: string] {
185
+ $"hello ($name)"
186
+ }
187
+
188
+ greet
189
+ ```
190
+
191
+ Making a positional parameter optional does not change its name when accessed in the body. As the example above shows, it is still accessed with `$name`, despite the `?` suffix in the parameter list.
192
+
193
+ When an optional parameter is not passed, its value in the command body is equal to `null`. We can use this to act on the case where a parameter was not passed:
194
+
195
+ ```nu
196
+ def greet [name?: string] {
197
+ if ($name == null) {
198
+ "hello, I don't know your name!"
199
+ } else {
200
+ $"hello ($name)"
201
+ }
202
+ }
203
+
204
+ greet
205
+ ```
206
+
207
+ If you just want to set a default value when the parameter is missing it is simpler to use a [default value](#parameters-with-a-default-value) instead.
208
+
209
+ If required and optional positional parameters are used together, then the required parameters must appear in the definition first.
210
+
211
+ ## Flags
212
+
213
+ In addition to passing positional parameters, you can also pass named parameters by defining flags for your custom commands.
214
+
215
+ For example:
216
+
217
+ ```nu
218
+ def greet [
219
+ name: string
220
+ --age: int
221
+ ] {
222
+ [$name $age]
223
+ }
224
+ ```
225
+
226
+ In the `greet` definition above, we define the `name` positional parameter as well as an `age` flag. This allows the caller of `greet` to optionally pass the `age` parameter as well.
227
+
228
+ You can call the above using:
229
+
230
+ ```nu
231
+ > greet world --age 10
232
+ ```
233
+
234
+ Or:
235
+
236
+ ```nu
237
+ > greet --age 10 world
238
+ ```
239
+
240
+ Or even leave the flag off altogether:
241
+
242
+ ```nu
243
+ > greet world
244
+ ```
245
+
246
+ Flags can also be defined to have a shorthand version. This allows you to pass a simpler flag as well as a longhand, easier-to-read flag.
247
+
248
+ Let's extend the previous example to use a shorthand flag for the `age` value:
249
+
250
+ ```nu
251
+ def greet [
252
+ name: string
253
+ --age (-a): int
254
+ ] {
255
+ [$name $age]
256
+ }
257
+ ```
258
+
259
+ _Note:_ Flags are named by their longhand name, so the above example would need to use `$age` and not `$a`.
260
+
261
+ Now, we can call this updated definition using the shorthand flag:
262
+
263
+ ```nu
264
+ > greet -a 10 hello
265
+ ```
266
+
267
+ Flags can also be used as basic switches. This means that their presence or absence is taken as an argument for the definition. Extending the previous example:
268
+
269
+ ```nu
270
+ def greet [
271
+ name: string
272
+ --age (-a): int
273
+ --twice
274
+ ] {
275
+ if $twice {
276
+ [$name $name $age $age]
277
+ } else {
278
+ [$name $age]
279
+ }
280
+ }
281
+ ```
282
+
283
+ And the definition can be either called as:
284
+
285
+ ```nu
286
+ > greet -a 10 --twice hello
287
+ ```
288
+
289
+ Or just without the switch flag:
290
+
291
+ ```nu
292
+ > greet -a 10 hello
293
+ ```
294
+
295
+ You can also assign it to true/false to enable/disable the flag too:
296
+
297
+ ```nu
298
+ > greet -a 10 --switch=false
299
+ > greet -a 10 --switch=true
300
+ ```
301
+
302
+ But note that this is not the behavior you want: `> greet -a 10 --switch false`, here the value `false` will pass as a positional argument.
303
+
304
+ To avoid confusion, it's not allowed to annotate a boolean type on a flag:
305
+
306
+ ```nu
307
+ def greet [
308
+ --twice: bool # Not allowed
309
+ ] { ... }
310
+ ```
311
+
312
+ instead, you should define it as a basic switch: `def greet [--twice] { ... }`
313
+
314
+ Flags can contain dashes. They can be accessed by replacing the dash with an underscore:
315
+
316
+ ```nu
317
+ def greet [
318
+ name: string
319
+ --age (-a): int
320
+ --two-times
321
+ ] {
322
+ if $two_times {
323
+ [$name $name $age $age]
324
+ } else {
325
+ [$name $age]
326
+ }
327
+ }
328
+ ```
329
+
330
+ ## Rest parameters
331
+
332
+ There may be cases when you want to define a command which takes any number of positional arguments. We can do this with a rest parameter, using the following `...` syntax:
333
+
334
+ ```nu
335
+ def greet [...name: string] {
336
+ print "hello all:"
337
+ for $n in $name {
338
+ print $n
339
+ }
340
+ }
341
+
342
+ greet earth mars jupiter venus
343
+ ```
344
+
345
+ We could call the above definition of the `greet` command with any number of arguments, including none at all. All of the arguments are collected into `$name` as a list.
346
+
347
+ Rest parameters can be used together with positional parameters:
348
+
349
+ ```nu
350
+ def greet [vip: string, ...name: string] {
351
+ print $"hello to our VIP ($vip)"
352
+ print "and hello to everybody else:"
353
+ for $n in $name {
354
+ print $n
355
+ }
356
+ }
357
+
358
+ # $vip $name
359
+ # ---- ------------------------
360
+ greet moon earth mars jupiter venus
361
+ ```
362
+
363
+ To pass a list to a rest parameter, you can use the [spread operator](/book/operators#spread-operator) (`...`):
364
+
365
+ ```nu
366
+ > let planets = [earth mars jupiter venus] # This is equivalent to the previous example
367
+ > greet moon ...$planets
368
+ ```
369
+
370
+ ## Documenting your command
371
+
372
+ In order to best help users of your custom commands, you can also document them with additional descriptions for the commands and parameters.
373
+
374
+ Taking our previous example:
375
+
376
+ ```nu
377
+ def greet [
378
+ name: string
379
+ --age (-a): int
380
+ ] {
381
+ [$name $age]
382
+ }
383
+ ```
384
+
385
+ Once defined, we can run `help greet` to get the help information for the command:
386
+
387
+ ```nu
388
+ Usage:
389
+ > greet <name> {flags}
390
+
391
+ Parameters:
392
+ <name>
393
+
394
+ Flags:
395
+ -h, --help: Display this help message
396
+ -a, --age <integer>
397
+ ```
398
+
399
+ You can see the parameter and flag that we defined, as well as the `-h` help flag that all commands get.
400
+
401
+ To improve this help, we can add descriptions to our definition that will show up in the help:
402
+
403
+ ```nu
404
+ # A greeting command that can greet the caller
405
+ def greet [
406
+ name: string # The name of the person to greet
407
+ --age (-a): int # The age of the person
408
+ ] {
409
+ [$name $age]
410
+ }
411
+ ```
412
+
413
+ The comments that we put on the definition and its parameters then appear as descriptions inside the [`help`](/commands/docs/help.md) of the command.
414
+
415
+ ::: warning Note
416
+ A Nushell comment that continues on the same line for argument documentation purposes requires a space before the ` #` pound sign.
417
+ :::
418
+
419
+ Now, if we run `help greet`, we're given a more helpful help text:
420
+
421
+ ```
422
+ A greeting command that can greet the caller
423
+
424
+ Usage:
425
+ > greet <name> {flags}
426
+
427
+ Parameters:
428
+ <name> The name of the person to greet
429
+
430
+ Flags:
431
+ -h, --help: Display this help message
432
+ -a, --age <integer>: The age of the person
433
+ ```
434
+
435
+ ## Pipeline Output
436
+
437
+ Custom commands stream their output just like built-in commands. For example, let's say we wanted to refactor this pipeline:
438
+
439
+ ```nu
440
+ > ls | get name
441
+ ```
442
+
443
+ Let's move [`ls`](/commands/docs/ls.md) into a command that we've written:
444
+
445
+ ```nu
446
+ def my-ls [] { ls }
447
+ ```
448
+
449
+ We can use the output from this command just as we would [`ls`](/commands/docs/ls.md).
450
+
451
+ ```nu
452
+ > my-ls | get name
453
+ ───┬───────────────────────
454
+ 0 │ myscript.nu
455
+ 1 │ myscript2.nu
456
+ 2 │ welcome_to_nushell.md
457
+ ───┴───────────────────────
458
+ ```
459
+
460
+ This lets us easily build custom commands and process their output. Note, that we don't use return statements like other languages. Instead, we build pipelines that output streams of data that can be connected to other pipelines.
461
+
462
+ ## Pipeline Input
463
+
464
+ Custom commands can also take input from the pipeline, just like other commands. This input is automatically passed to the block that the custom command uses.
465
+
466
+ Let's make our own command that doubles every value it receives as input:
467
+
468
+ ```nu
469
+ def double [] {
470
+ each { |it| 2 * $it }
471
+ }
472
+ ```
473
+
474
+ Now, if we call the above command later in a pipeline, we can see what it does with the input:
475
+
476
+ ```nu
477
+ > [1 2 3] | double
478
+ ───┬─────
479
+ 0 │ 2
480
+ 1 │ 4
481
+ 2 │ 6
482
+ ───┴─────
483
+ ```
484
+
485
+ We can also store the input for later use using the `$in` variable:
486
+
487
+ ```nu
488
+ def nullify [...cols] {
489
+ let start = $in
490
+ $cols | reduce --fold $start { |col, df|
491
+ $df | upsert $col null
492
+ }
493
+ }
494
+ ```
495
+
496
+ ## Persisting
497
+
498
+ For information about how to persist custom commands so that they're visible when you start up Nushell, see the [configuration chapter](configuration.md) and add your startup script.
custom_completions.md ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Custom completions
2
+
3
+ Custom completions allow you to mix together two features of Nushell: custom commands and completions. With them, you're able to create commands that handle the completions for positional parameters and flag parameters. These custom completions work both for [custom commands](custom_commands.md) and [known external, or `extern`, commands](externs.md).
4
+
5
+ There are two parts to a custom command: the command that handles a completion and attaching this command to the type of another command using `@`.
6
+
7
+ ## Example custom completion
8
+
9
+ Let's look at an example:
10
+
11
+ ```nu
12
+ > def animals [] { ["cat", "dog", "eel" ] }
13
+ > def my-command [animal: string@animals] { print $animal }
14
+ >| my-command
15
+ cat dog eel
16
+ ```
17
+
18
+ In the first line, we create a custom command that will return a list of three different animals. These are the values we'd like to use in the completion. Once we've created this command, we can now use it to provide completions for other custom commands and [`extern`](/commands/docs/extern.md)s.
19
+
20
+ In the second line, we use `string@animals`. This tells Nushell two things: the shape of the argument for type-checking and the custom completion to use if the user wants to complete values at that position.
21
+
22
+ On the third line, we type the name of our custom command `my-command` followed by hitting space and then the `<tab>` key. This brings up our completions. Custom completions work the same as other completions in the system, allowing you to type `e` followed by the `<tab>` key and get "eel" automatically completed.
23
+
24
+ ## Modules and custom completions
25
+
26
+ You may prefer to keep your custom completions away from the public API for your code. For this, you can combine modules and custom completions.
27
+
28
+ Let's take the example above and put it into a module:
29
+
30
+ ```nu
31
+ module commands {
32
+ def animals [] {
33
+ ["cat", "dog", "eel" ]
34
+ }
35
+
36
+ export def my-command [animal: string@animals] {
37
+ print $animal
38
+ }
39
+ }
40
+ ```
41
+
42
+ In our module, we've chosen to export only the custom command `my-command` but not the custom completion `animals`. This allows users of this module to call the command, and even use the custom completion logic, without having access to the custom completion. This keeps the API cleaner, while still offering all the same benefits.
43
+
44
+ This is possible because custom completion tags using `@` are locked-in as the command is first parsed.
45
+
46
+ ## Context aware custom completions
47
+
48
+ It is possible to pass the context to the custom completion command. This is useful in situations where it is necessary to know previous arguments or flags to generate accurate completions.
49
+
50
+ Let's apply this concept to the previous example:
51
+
52
+ ```nu
53
+ module commands {
54
+ def animals [] {
55
+ ["cat", "dog", "eel" ]
56
+ }
57
+
58
+ def animal-names [context: string] {
59
+ {
60
+ cat: ["Missy", "Phoebe"]
61
+ dog: ["Lulu", "Enzo"]
62
+ eel: ["Eww", "Slippy"]
63
+ } | get -i ($context | split words | last)
64
+ }
65
+
66
+ export def my-command [
67
+ animal: string@animals
68
+ name: string@animal-names
69
+ ] {
70
+ print $"The ($animal) is named ($name)."
71
+ }
72
+ }
73
+ ```
74
+
75
+ Here, the command `animal-names` returns the appropriate list of names. This is because `$context` is a string with where the value is the command that has been typed until now.
76
+
77
+ ```nu
78
+ >| my-command
79
+ cat dog eel
80
+ >| my-command dog
81
+ Lulu Enzo
82
+ >my-command dog enzo
83
+ The dog is named Enzo
84
+ ```
85
+
86
+ On the second line, once we press the `<tab>` key, the argument `"my-command dog"` is passed to the `animal-names` command as context.
87
+
88
+ ## Custom completion and [`extern`](/commands/docs/extern.md)
89
+
90
+ A powerful combination is adding custom completions to [known `extern` commands](externs.md). These work the same way as adding a custom completion to a custom command: by creating the custom completion and then attaching it with a `@` to the type of one of the positional or flag arguments of the `extern`.
91
+
92
+ If you look closely at the examples in the default config, you'll see this:
93
+
94
+ ```nu
95
+ export extern "git push" [
96
+ remote?: string@"nu-complete git remotes", # the name of the remote
97
+ refspec?: string@"nu-complete git branches" # the branch / refspec
98
+ ...
99
+ ]
100
+ ```
101
+
102
+ Custom completions will serve the same role in this example as in the previous examples. The examples above call into two different custom completions, based on the position the user is currently in.
103
+
104
+ ## Custom descriptions
105
+
106
+ As an alternative to returning a list of strings, a completion function can also return a list of records with a `value` and `description` field.
107
+
108
+ ```nu
109
+ def my_commits [] {
110
+ [
111
+ { value: "5c2464", description: "Add .gitignore" },
112
+ { value: "f3a377", description: "Initial commit" }
113
+ ]
114
+ }
115
+ ```
116
+
117
+ > **Note**
118
+ >
119
+ > with the following snippet
120
+ >
121
+ > ```nu
122
+ > def my-command [commit: string@my_commits] {
123
+ > print $commit
124
+ > }
125
+ > ```
126
+ >
127
+ > be aware that, even though the completion menu will show you something like
128
+ >
129
+ > ```nu
130
+ > >_ my-command <TAB>
131
+ > 5c2464 Add .gitignore
132
+ > f3a377 Initial commit
133
+ > ```
134
+ >
135
+ > only the value, i.e. "5c2464" or "f3a377", will be used in the command arguments!
136
+
137
+ ## External completions
138
+
139
+ External completers can also be integrated, instead of relying solely on Nushell ones.
140
+
141
+ For this, set the `external_completer` field in `config.nu` to a [closure](types_of_data.md#closures) which will be evaluated if no Nushell completions were found.
142
+
143
+ ```nu
144
+ > $env.config.completions.external = {
145
+ > enable: true
146
+ > max_results: 100
147
+ > completer: $completer
148
+ > }
149
+ ```
150
+
151
+ You can configure the closure to run an external completer, such as [carapace](https://github.com/rsteube/carapace-bin).
152
+
153
+ When the closure returns unparsable json (e.g. an empty string) it defaults to file completion.
154
+
155
+ An external completer is a function that takes the current command as a string list, and outputs a list of records with `value` and `description` keys, like custom completion functions.
156
+
157
+ > **Note**
158
+ > This closure will accept the current command as a list. For example, typing `my-command --arg1 <tab>` will receive `[my-command --arg1 " "]`.
159
+
160
+ This example will enable carapace external completions:
161
+
162
+ ```nu
163
+ let carapace_completer = {|spans|
164
+ carapace $spans.0 nushell ...$spans | from json
165
+ }
166
+ ```
167
+
168
+ [More examples of custom completers can be found in the cookbook](../cookbook/external_completers.md).
dataframes.md ADDED
@@ -0,0 +1,1152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dataframes
2
+
3
+ ::: warning
4
+ To use the dataframe support you need a fully-featured build with `cargo build --features dataframe`. Starting with version 0.72, dataframes are *not* included with binary releases of Nushell. [See the installation instructions](/book/installation.md) for further details.
5
+ :::
6
+
7
+ As we have seen so far, Nushell makes working with data its main priority.
8
+ `Lists` and `Tables` are there to help you cycle through values in order to
9
+ perform multiple operations or find data in a breeze. However, there are
10
+ certain operations where a row-based data layout is not the most efficient way
11
+ to process data, especially when working with extremely large files. Operations
12
+ like group-by or join using large datasets can be costly memory-wise, and may
13
+ lead to large computation times if they are not done using the appropriate
14
+ data format.
15
+
16
+ For this reason, the `DataFrame` structure was introduced to Nushell. A
17
+ `DataFrame` stores its data in a columnar format using as its base the [Apache
18
+ Arrow](https://arrow.apache.org/) specification, and uses
19
+ [Polars](https://github.com/pola-rs/polars) as the motor for performing
20
+ extremely [fast columnar operations](https://h2oai.github.io/db-benchmark/).
21
+
22
+ You may be wondering now how fast this combo could be, and how could it make
23
+ working with data easier and more reliable. For this reason, let's start this
24
+ page by presenting benchmarks on common operations that are done when
25
+ processing data.
26
+
27
+ ## Benchmark comparisons
28
+
29
+ For this little benchmark exercise we will be comparing native Nushell
30
+ commands, dataframe Nushell commands and [Python
31
+ Pandas](https://pandas.pydata.org/) commands. For the time being don't pay too
32
+ much attention to the [`Dataframe` commands](/commands/categories/dataframe.md). They will be explained in later
33
+ sections of this page.
34
+
35
+ > System Details: The benchmarks presented in this section were run using a
36
+ > machine with a processor Intel(R) Core(TM) i7-10710U (CPU @1.10GHz 1.61 GHz)
37
+ > and 16 gb of RAM.
38
+ >
39
+ > All examples were run on Nushell version 0.33.1.
40
+ > (Command names are updated to Nushell 0.78)
41
+
42
+ ### File information
43
+
44
+ The file that we will be using for the benchmarks is the
45
+ [New Zealand business demography](https://www.stats.govt.nz/assets/Uploads/New-Zealand-business-demography-statistics/New-Zealand-business-demography-statistics-At-February-2020/Download-data/Geographic-units-by-industry-and-statistical-area-2000-2020-descending-order-CSV.zip) dataset.
46
+ Feel free to download it if you want to follow these tests.
47
+
48
+ The dataset has 5 columns and 5,429,252 rows. We can check that by using the
49
+ `dfr ls` command:
50
+
51
+ ```nu
52
+ ❯ let df = (dfr open .\Data7602DescendingYearOrder.csv)
53
+ ❯ dfr ls
54
+
55
+ ╭───┬────────┬─────────┬─────────╮
56
+ │ # │ name │ columns │ rows │
57
+ ├───┼────────┼─────────┼─────────┤
58
+ │ 0 │ $df │ 5 │ 5429252 │
59
+ ╰───┴────────┴─────────┴─────────╯
60
+ ```
61
+
62
+ We can have a look at the first lines of the file using [`first`](/commands/docs/first.md):
63
+
64
+ ```nu
65
+ ❯ $df | dfr first
66
+ ╭───┬──────────┬─────────┬──────┬───────────┬──────────╮
67
+ │ # │ anzsic06 │ Area │ year │ geo_count │ ec_count │
68
+ ├───┼──────────┼─────────┼──────┼───────────┼──────────┤
69
+ │ 0 │ A │ A100100 │ 2000 │ 96 │ 130 │
70
+ ╰───┴──────────┴─────────┴──────┴───────────┴──────────╯
71
+ ```
72
+
73
+ ...and finally, we can get an idea of the inferred data types:
74
+
75
+ ```nu
76
+ ❯ $df | dfr dtypes
77
+ ╭───┬───────────┬───────╮
78
+ │ # │ column │ dtype │
79
+ ├───┼───────────┼───────┤
80
+ │ 0 │ anzsic06 │ str │
81
+ │ 1 │ Area │ str │
82
+ │ 2 │ year │ i64 │
83
+ │ 3 │ geo_count │ i64 │
84
+ │ 4 │ ec_count │ i64 │
85
+ ╰───┴───────────┴───────╯
86
+ ```
87
+
88
+ ### Loading the file
89
+
90
+ Let's start by comparing loading times between the various methods. First, we
91
+ will load the data using Nushell's [`open`](/commands/docs/open.md) command:
92
+
93
+ ```nu
94
+ ❯ timeit {open .\Data7602DescendingYearOrder.csv}
95
+ 30sec 479ms 614us 400ns
96
+ ```
97
+
98
+ Loading the file using native Nushell functionality took 30 seconds. Not bad for
99
+ loading five million records! But we can do a bit better than that.
100
+
101
+ Let's now use Pandas. We are going to use the next script to load the file:
102
+
103
+ ```python
104
+ import pandas as pd
105
+
106
+ df = pd.read_csv("Data7602DescendingYearOrder.csv")
107
+ ```
108
+
109
+ And the benchmark for it is:
110
+
111
+ ```nu
112
+ ❯ timeit {python load.py}
113
+ 2sec 91ms 872us 900ns
114
+ ```
115
+
116
+ That is a great improvement, from 30 seconds to 2 seconds. Nicely done, Pandas!
117
+
118
+ Probably we can load the data a bit faster. This time we will use Nushell's
119
+ `dfr open` command:
120
+
121
+ ```nu
122
+ ❯ timeit {dfr open .\Data7602DescendingYearOrder.csv}
123
+ 601ms 700us 700ns
124
+ ```
125
+
126
+ This time it took us 0.6 seconds. Not bad at all.
127
+
128
+ ### Group-by comparison
129
+
130
+ Let's do a slightly more complex operation this time. We are going to group the
131
+ data by year, and add groups using the column `geo_count`.
132
+
133
+ Again, we are going to start with a Nushell native command.
134
+
135
+ ::: tip
136
+ If you want to run this example, be aware that the next command will
137
+ use a large amount of memory. This may affect the performance of your system
138
+ while this is being executed.
139
+ :::
140
+
141
+ ```nu
142
+ ❯ timeit {
143
+ open .\Data7602DescendingYearOrder.csv
144
+ | group-by year
145
+ | transpose header rows
146
+ | upsert rows { get rows | math sum }
147
+ | flatten
148
+ }
149
+
150
+ 6min 30sec 622ms 312us
151
+ ```
152
+
153
+ So, six minutes to perform this aggregated operation.
154
+
155
+ Let's try the same operation in pandas:
156
+
157
+ ```python
158
+ import pandas as pd
159
+
160
+ df = pd.read_csv("Data7602DescendingYearOrder.csv")
161
+ res = df.groupby("year")["geo_count"].sum()
162
+ print(res)
163
+ ```
164
+
165
+ And the result from the benchmark is:
166
+
167
+ ```nu
168
+ ❯ timeit {python .\load.py}
169
+
170
+ 1sec 966ms 954us 800ns
171
+ ```
172
+
173
+ Not bad at all. Again, pandas managed to get it done in a fraction of the time.
174
+
175
+ To finish the comparison, let's try Nushell dataframes. We are going to put
176
+ all the operations in one `nu` file, to make sure we are doing similar
177
+ operations:
178
+
179
+ ```nu
180
+ let df = (dfr open Data7602DescendingYearOrder.csv)
181
+ let res = ($df | dfr group-by year | dfr agg (dfr col geo_count | dfr sum))
182
+ $res
183
+ ```
184
+
185
+ and the benchmark with dataframes is:
186
+
187
+ ```nu
188
+ ❯ timeit {source load.nu}
189
+
190
+ 557ms 658us 500ns
191
+ ```
192
+
193
+ Luckily Nushell dataframes managed to halve the time again. Isn't that great?
194
+
195
+ As you can see, Nushell's [`Dataframe` commands](/commands/categories/dataframe.md)
196
+ are as fast as the most common tools that exist today to do data analysis. The commands
197
+ that are included in this release have the potential to become your go-to tool for
198
+ doing data analysis. By composing complex Nushell pipelines, you can extract information
199
+ from data in a reliable way.
200
+
201
+ ## Working with Dataframes
202
+
203
+ After seeing a glimpse of the things that can be done with [`Dataframe` commands](/commands/categories/dataframe.md),
204
+ now it is time to start testing them. To begin let's create a sample
205
+ CSV file that will become our sample dataframe that we will be using along with
206
+ the examples. In your favorite file editor paste the next lines to create out
207
+ sample csv file.
208
+
209
+ ```
210
+ int_1,int_2,float_1,float_2,first,second,third,word
211
+ 1,11,0.1,1.0,a,b,c,first
212
+ 2,12,0.2,1.0,a,b,c,second
213
+ 3,13,0.3,2.0,a,b,c,third
214
+ 4,14,0.4,3.0,b,a,c,second
215
+ 0,15,0.5,4.0,b,a,a,third
216
+ 6,16,0.6,5.0,b,a,a,second
217
+ 7,17,0.7,6.0,b,c,a,third
218
+ 8,18,0.8,7.0,c,c,b,eight
219
+ 9,19,0.9,8.0,c,c,b,ninth
220
+ 0,10,0.0,9.0,c,c,b,ninth
221
+ ```
222
+
223
+ Save the file and name it however you want to, for the sake of these examples
224
+ the file will be called `test_small.csv`.
225
+
226
+ Now, to read that file as a dataframe use the `dfr open` command like
227
+ this:
228
+
229
+ ```nu
230
+ ❯ let df = (dfr open test_small.csv)
231
+ ```
232
+
233
+ This should create the value `$df` in memory which holds the data we just
234
+ created.
235
+
236
+ ::: tip
237
+ The command `dfr open` can read either **csv** or **parquet**
238
+ files.
239
+ :::
240
+
241
+ To see all the dataframes that are stored in memory you can use
242
+
243
+ ```nu
244
+ ❯ dfr ls
245
+ ╭───┬──────┬─────────┬──────╮
246
+ │ # │ name │ columns │ rows │
247
+ ├───┼──────┼─────────┼──────┤
248
+ │ 0 │ $df │ 8 │ 10 │
249
+ ╰───┴──────┴─────────┴──────╯
250
+ ```
251
+
252
+ As you can see, the command shows the created dataframes together with basic
253
+ information about them.
254
+
255
+ And if you want to see a preview of the loaded dataframe you can send the
256
+ dataframe variable to the stream
257
+
258
+ ```nu
259
+ ❯ $df
260
+ ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────────╮
261
+ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │
262
+ ├───┼───────┼───────┼─────────┼─────────┼───────┼────────┼───────┼────────┤
263
+ │ 0 │ 1 │ 11 │ 0.10 │ 1.00 │ a │ b │ c │ first │
264
+ │ 1 │ 2 │ 12 │ 0.20 │ 1.00 │ a │ b │ c │ second │
265
+ │ 2 │ 3 │ 13 │ 0.30 │ 2.00 │ a │ b │ c │ third │
266
+ │ 3 │ 4 │ 14 │ 0.40 │ 3.00 │ b │ a │ c │ second │
267
+ │ 4 │ 0 │ 15 │ 0.50 │ 4.00 │ b │ a │ a │ third │
268
+ │ 5 │ 6 │ 16 │ 0.60 │ 5.00 │ b │ a │ a │ second │
269
+ │ 6 │ 7 │ 17 │ 0.70 │ 6.00 │ b │ c │ a │ third │
270
+ │ 7 │ 8 │ 18 │ 0.80 │ 7.00 │ c │ c │ b │ eight │
271
+ │ 8 │ 9 │ 19 │ 0.90 │ 8.00 │ c │ c │ b │ ninth │
272
+ │ 9 │ 0 │ 10 │ 0.00 │ 9.00 │ c │ c │ b │ ninth │
273
+ ╰───┴───────┴───────┴─────────┴─────────┴───────┴────────┴───────┴────────╯
274
+ ```
275
+
276
+ With the dataframe in memory we can start doing column operations with the
277
+ `DataFrame`
278
+
279
+ ::: tip
280
+ If you want to see all the dataframe commands that are available you
281
+ can use `scope commands | where category =~ dataframe`
282
+ :::
283
+
284
+ ## Basic aggregations
285
+
286
+ Let's start with basic aggregations on the dataframe. Let's sum all the columns
287
+ that exist in `df` by using the `aggregate` command
288
+
289
+ ```nu
290
+ ❯ $df | dfr sum
291
+ ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬──────╮
292
+ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │
293
+ ├───┼───────┼───────┼─────────┼─────────┼───────┼────────┼───────┼──────┤
294
+ │ 0 │ 40 │ 145 │ 4.50 │ 46.00 │ │ │ │ │
295
+ ╰───┴───────┴───────┴─────────┴─────────┴───────┴────────┴───────┴──────╯
296
+ ```
297
+
298
+ As you can see, the aggregate function computes the sum for those columns where
299
+ a sum makes sense. If you want to filter out the text column, you can select
300
+ the columns you want by using the [`dfr select`](/commands/docs/dfr_select.md) command
301
+
302
+ ```nu
303
+ ❯ $df | dfr sum | dfr select int_1 int_2 float_1 float_2
304
+ ╭───┬───────┬───────┬─────────┬─────────╮
305
+ │ # │ int_1 │ int_2 │ float_1 │ float_2 │
306
+ ├───┼───────┼───────┼─────────┼─────────┤
307
+ │ 0 │ 40 │ 145 │ 4.50 │ 46.00 │
308
+ ╰───┴───────┴───────┴─────────┴─────────╯
309
+ ```
310
+
311
+ You can even store the result from this aggregation as you would store any
312
+ other Nushell variable
313
+
314
+ ```nu
315
+ ❯ let res = ($df | dfr sum | dfr select int_1 int_2 float_1 float_2)
316
+ ```
317
+
318
+ ::: tip
319
+ Type `let res = ( !! )` and press enter. This will auto complete the previously
320
+ executed command. Note the space between ( and !!.
321
+ :::
322
+
323
+ And now we have two dataframes stored in memory
324
+
325
+ ```nu
326
+ ❯ dfr ls
327
+ ╭───┬──────┬─────────┬──────╮
328
+ │ # │ name │ columns │ rows │
329
+ ├───┼──────┼─────────┼──────┤
330
+ │ 0 │ $res │ 4 │ 1 │
331
+ │ 1 │ $df │ 8 │ 10 │
332
+ ╰───┴──────┴─────────┴──────╯
333
+ ```
334
+
335
+ Pretty neat, isn't it?
336
+
337
+ You can perform several aggregations on the dataframe in order to extract basic
338
+ information from the dataframe and do basic data analysis on your brand new
339
+ dataframe.
340
+
341
+ ## Joining a DataFrame
342
+
343
+ It is also possible to join two dataframes using a column as reference. We are
344
+ going to join our mini dataframe with another mini dataframe. Copy these lines
345
+ in another file and create the corresponding dataframe (for these examples we
346
+ are going to call it `test_small_a.csv`)
347
+
348
+ ```
349
+ int_1,int_2,float_1,float_2,first
350
+ 9,14,0.4,3.0,a
351
+ 8,13,0.3,2.0,a
352
+ 7,12,0.2,1.0,a
353
+ 6,11,0.1,0.0,b
354
+ ```
355
+
356
+ We use the `dfr open` command to create the new variable
357
+
358
+ ```nu
359
+ ❯ let df_a = (dfr open test_small_a.csv)
360
+ ```
361
+
362
+ Now, with the second dataframe loaded in memory we can join them using the
363
+ column called `int_1` from the left dataframe and the column `int_1` from the
364
+ right dataframe
365
+
366
+ ```nu
367
+ ❯ $df | dfr join $df_a int_1 int_1
368
+ ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────────┬─────────┬───────────┬───────────┬─────────╮
369
+ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │ int_2_x │ float_1_x │ float_2_x │ first_x │
370
+ ├───┼───────┼───────┼─────────┼─────────┼───────┼────────┼───────┼────────┼─────────┼───────────┼───────────┼─────────┤
371
+ │ 0 │ 6 │ 16 │ 0.60 │ 5.00 │ b │ a │ a │ second │ 11 │ 0.10 │ 0.00 │ b │
372
+ │ 1 │ 7 │ 17 │ 0.70 │ 6.00 │ b │ c │ a │ third │ 12 │ 0.20 │ 1.00 │ a │
373
+ │ 2 │ 8 │ 18 │ 0.80 │ 7.00 │ c │ c │ b │ eight │ 13 │ 0.30 │ 2.00 │ a │
374
+ │ 3 │ 9 │ 19 │ 0.90 │ 8.00 │ c │ c │ b │ ninth │ 14 │ 0.40 │ 3.00 │ a │
375
+ ╰───┴───────┴───────┴─────────┴─────────┴───────┴────────┴───────┴────────┴─────────┴───────────┴───────────┴─────────╯
376
+ ```
377
+
378
+ ::: tip
379
+ In `Nu` when a command has multiple arguments that are expecting
380
+ multiple values we use brackets `[]` to enclose those values. In the case of
381
+ [`dfr join`](/commands/docs/dfr_join.md) we can join on multiple columns
382
+ as long as they have the same type.
383
+ :::
384
+
385
+ For example:
386
+
387
+ ```nu
388
+ ❯ $df | dfr join $df_a [int_1 first] [int_1 first]
389
+ ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────────┬─────────┬───────────┬───────────╮
390
+ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │ int_2_x │ float_1_x │ float_2_x │
391
+ ├───┼───────┼───────┼─────────┼─────────┼───────┼────────┼───────┼────────┼─────────┼───────────┼───────────┤
392
+ │ 0 │ 6 │ 16 │ 0.60 │ 5.00 │ b │ a │ a │ second │ 11 │ 0.10 │ 0.00 │
393
+ ╰───┴───────┴───────┴─────────┴─────────┴───────┴────────┴───────┴────────┴─────────┴───────────┴───────────╯
394
+ ```
395
+
396
+ By default, the join command does an inner join, meaning that it will keep the
397
+ rows where both dataframes share the same value. You can select a left join to
398
+ keep the missing rows from the left dataframe. You can also save this result
399
+ in order to use it for further operations.
400
+
401
+ ## DataFrame group-by
402
+
403
+ One of the most powerful operations that can be performed with a DataFrame is
404
+ the [`dfr group-by`](/commands/docs/dfr_group-by.md). This command will allow you to perform aggregation operations
405
+ based on a grouping criteria. In Nushell, a `GroupBy` is a type of object that
406
+ can be stored and reused for multiple aggregations. This is quite handy, since
407
+ the creation of the grouped pairs is the most expensive operation while doing
408
+ group-by and there is no need to repeat it if you are planning to do multiple
409
+ operations with the same group condition.
410
+
411
+ To create a `GroupBy` object you only need to use the [`dfr_group-by`](/commands/docs/dfr_group-by.md) command
412
+
413
+ ```nu
414
+ ❯ let group = ($df | dfr group-by first)
415
+ ❯ $group
416
+ ╭─────────────┬──────────────────────────────────────────────╮
417
+ │ LazyGroupBy │ apply aggregation to complete execution plan │
418
+ ╰─────────────┴──────────────────────────────────────────────╯
419
+ ```
420
+
421
+ When printing the `GroupBy` object we can see that it is in the background a
422
+ lazy operation waiting to be completed by adding an aggregation. Using the
423
+ `GroupBy` we can create aggregations on a column
424
+
425
+ ```nu
426
+ ❯ $group | dfr agg (dfr col int_1 | dfr sum)
427
+ ╭───┬───────┬───────╮
428
+ │ # │ first │ int_1 │
429
+ ├───┼───────┼───────┤
430
+ │ 0 │ b │ 17 │
431
+ │ 1 │ a │ 6 │
432
+ │ 2 │ c │ 17 │
433
+ ╰───┴───────┴───────╯
434
+ ```
435
+
436
+ or we can define multiple aggregations on the same or different columns
437
+
438
+ ```nu
439
+ ❯ $group | dfr agg [
440
+ ∙ (dfr col int_1 | dfr n-unique)
441
+ ∙ (dfr col int_2 | dfr min)
442
+ ∙ (dfr col float_1 | dfr sum)
443
+ ∙ (dfr col float_2 | dfr count)
444
+ ∙ ] | dfr sort-by first
445
+ ╭───┬───────┬───────┬───────┬─────────┬─────────╮
446
+ │ # │ first │ int_1 │ int_2 │ float_1 │ float_2 │
447
+ ├───┼───────┼───────┼───────┼─────────┼─────────┤
448
+ │ 0 │ a │ 3 │ 11 │ 0.60 │ 3 │
449
+ │ 1 │ b │ 4 │ 14 │ 2.20 │ 4 │
450
+ │ 2 │ c │ 3 │ 10 │ 1.70 │ 3 │
451
+ ╰───┴───────┴───────┴───────┴─────────┴─────────╯
452
+ ```
453
+
454
+ As you can see, the `GroupBy` object is a very powerful variable and it is
455
+ worth keeping in memory while you explore your dataset.
456
+
457
+ ## Creating Dataframes
458
+
459
+ It is also possible to construct dataframes from basic Nushell primitives, such
460
+ as integers, decimals, or strings. Let's create a small dataframe using the
461
+ command `dfr into-df`.
462
+
463
+ ```nu
464
+ ❯ let a = ([[a b]; [1 2] [3 4] [5 6]] | dfr into-df)
465
+ ❯ $a
466
+ ```
467
+
468
+ ::: tip
469
+ For the time being, not all of Nushell primitives can be converted into
470
+ a dataframe. This will change in the future, as the dataframe feature matures
471
+ :::
472
+
473
+ We can append columns to a dataframe in order to create a new variable. As an
474
+ example, let's append two columns to our mini dataframe `$a`
475
+
476
+ ```nu
477
+ ❯ let a2 = ($a | dfr with-column $a.a --name a2 | dfr with-column $a.a --name a3)
478
+ ❯ $a2
479
+ ╭───┬───┬───┬────┬────╮
480
+ │ # │ a │ b │ a2 │ a3 │
481
+ ├───┼───┼───┼────┼────┤
482
+ │ 0 │ 1 │ 2 │ 1 │ 1 │
483
+ │ 1 │ 3 │ 4 │ 3 │ 3 │
484
+ │ 2 │ 5 │ 6 │ 5 │ 5 │
485
+ ╰───┴───┴───┴────┴────╯
486
+ ```
487
+
488
+ Nushell's powerful piping syntax allows us to create new dataframes by
489
+ taking data from other dataframes and appending it to them. Now, if you list your
490
+ dataframes you will see in total four dataframes
491
+
492
+ ```nu
493
+ ❯ dfr ls
494
+ ╭───┬───────┬─────────┬──────╮
495
+ │ # │ name │ columns │ rows │
496
+ ├───┼───────┼─────────┼──────┤
497
+ │ 0 │ $a2 │ 4 │ 3 │
498
+ │ 1 │ $df_a │ 5 │ 4 │
499
+ │ 2 │ $df │ 8 │ 10 │
500
+ │ 3 │ $a │ 2 │ 3 │
501
+ │ 4 │ $res │ 4 │ 1 │
502
+ ╰───┴───────┴─────────┴──────╯
503
+ ```
504
+
505
+ One thing that is important to mention is how the memory is being optimized
506
+ while working with dataframes, and this is thanks to **Apache Arrow** and
507
+ **Polars**. In a very simple representation, each column in a DataFrame is an
508
+ Arrow Array, which is using several memory specifications in order to maintain
509
+ the data as packed as possible (check [Arrow columnar
510
+ format](https://arrow.apache.org/docs/format/Columnar.html)). The other
511
+ optimization trick is the fact that whenever possible, the columns from the
512
+ dataframes are shared between dataframes, avoiding memory duplication for the
513
+ same data. This means that dataframes `$a` and `$a2` are sharing the same two
514
+ columns we created using the `dfr into-df` command. For this reason, it isn't
515
+ possible to change the value of a column in a dataframe. However, you can
516
+ create new columns based on data from other columns or dataframes.
517
+
518
+ ## Working with Series
519
+
520
+ A `Series` is the building block of a `DataFrame`. Each Series represents a
521
+ column with the same data type, and we can create multiple Series of different
522
+ types, such as float, int or string.
523
+
524
+ Let's start our exploration with Series by creating one using the `dfr into-df`
525
+ command:
526
+
527
+ ```nu
528
+ ❯ let new = ([9 8 4] | dfr into-df)
529
+ ❯ $new
530
+ ╭───┬───╮
531
+ │ # │ 0 │
532
+ ├───┼───┤
533
+ │ 0 │ 9 │
534
+ │ 1 │ 8 │
535
+ │ 2 │ 4 │
536
+ ╰───┴───╯
537
+ ```
538
+
539
+ We have created a new series from a list of integers (we could have done the
540
+ same using floats or strings)
541
+
542
+ Series have their own basic operations defined, and they can be used to create
543
+ other Series. Let's create a new Series by doing some arithmetic on the
544
+ previously created column.
545
+
546
+ ```nu
547
+ ❯ let new_2 = ($new * 3 + 10)
548
+ ❯ $new_2
549
+ ╭───┬────╮
550
+ │ # │ 0 │
551
+ ├───┼────┤
552
+ │ 0 │ 37 │
553
+ │ 1 │ 34 │
554
+ │ 2 │ 22 │
555
+ ╰───┴────╯
556
+ ```
557
+
558
+ Now we have a new Series that was constructed by doing basic operations on the
559
+ previous variable.
560
+
561
+ ::: tip
562
+ If you want to see how many variables you have stored in memory you can
563
+ use `scope variables`
564
+ :::
565
+
566
+ Let's rename our previous Series so it has a memorable name
567
+
568
+ ```nu
569
+ ❯ let new_2 = ($new_2 | dfr rename "0" memorable)
570
+ ❯ $new_2
571
+ ╭───┬───────────╮
572
+ │ # │ memorable │
573
+ ├───┼───────────┤
574
+ │ 0 │ 37 │
575
+ │ 1 │ 34 │
576
+ │ 2 │ 22 │
577
+ ╰───┴───────────╯
578
+ ```
579
+
580
+ We can also do basic operations with two Series as long as they have the same
581
+ data type
582
+
583
+ ```nu
584
+ ❯ $new - $new_2
585
+ ╭───┬─────────────────╮
586
+ │ # │ sub_0_memorable │
587
+ ├───┼─────────────────┤
588
+ │ 0 │ -28 │
589
+ │ 1 │ -26 │
590
+ │ 2 │ -18 │
591
+ ╰───┴─────────────────╯
592
+ ```
593
+
594
+ And we can add them to previously defined dataframes
595
+
596
+ ```nu
597
+ ❯ let new_df = ($a | dfr with-column $new --name new_col)
598
+ ❯ $new_df
599
+ ╭───┬───┬───┬─────────╮
600
+ │ # │ a │ b │ new_col │
601
+ ├───┼───┼───┼─────────┤
602
+ │ 0 │ 1 │ 2 │ 9 │
603
+ │ 1 │ 3 │ 4 │ 8 │
604
+ │ 2 │ 5 │ 6 │ 4 │
605
+ ╰───┴───┴───┴─────────╯
606
+ ```
607
+
608
+ The Series stored in a Dataframe can also be used directly, for example,
609
+ we can multiply columns `a` and `b` to create a new Series
610
+
611
+ ```nu
612
+ ❯ $new_df.a * $new_df.b
613
+ ╭───┬─────────╮
614
+ │ # │ mul_a_b │
615
+ ├───┼─────────┤
616
+ │ 0 │ 2 │
617
+ │ 1 │ 12 │
618
+ │ 2 │ 30 │
619
+ ╰───┴─────────╯
620
+ ```
621
+
622
+ and we can start piping things in order to create new columns and dataframes
623
+
624
+ ```nu
625
+ ❯ let $new_df = ($new_df | dfr with-column ($new_df.a * $new_df.b / $new_df.new_col) --name my_sum)
626
+ ❯ $new_df
627
+ ╭───┬───┬───┬─────────┬────────╮
628
+ │ # │ a │ b │ new_col │ my_sum │
629
+ ├───┼───┼───┼─────────┼────────┤
630
+ │ 0 │ 1 │ 2 │ 9 │ 0 │
631
+ │ 1 │ 3 │ 4 │ 8 │ 1 │
632
+ │ 2 │ 5 │ 6 │ 4 │ 7 │
633
+ ╰───┴───┴───┴─────────┴────────╯
634
+ ```
635
+
636
+ Nushell's piping system can help you create very interesting workflows.
637
+
638
+ ## Series and masks
639
+
640
+ Series have another key use in when working with `DataFrames`, and it is the fact
641
+ that we can build boolean masks out of them. Let's start by creating a simple
642
+ mask using the equality operator
643
+
644
+ ```nu
645
+ ❯ let mask = ($new == 8)
646
+ ❯ $mask
647
+ ╭───┬───────╮
648
+ │ # │ 0 │
649
+ ├───┼───────┤
650
+ │ 0 │ false │
651
+ │ 1 │ true │
652
+ │ 2 │ false │
653
+ ╰───┴───────╯
654
+ ```
655
+
656
+ and with this mask we can now filter a dataframe, like this
657
+
658
+ ```nu
659
+ ❯ $new_df | dfr filter-with $mask
660
+ ╭───┬───┬───┬─────────┬────────╮
661
+ │ # │ a │ b │ new_col │ my_sum │
662
+ ├───┼───┼───┼─────────┼────────┤
663
+ │ 0 │ 3 │ 4 │ 8 │ 1 │
664
+ ╰───┴───┴───┴─────────┴────────╯
665
+ ```
666
+
667
+ Now we have a new dataframe with only the values where the mask was true.
668
+
669
+ The masks can also be created from Nushell lists, for example:
670
+
671
+ ```nu
672
+ ❯ let mask1 = ([true true false] | dfr into-df)
673
+ ❯ $new_df | dfr filter-with $mask1
674
+ ╭───┬───┬───┬─────────┬────────╮
675
+ │ # │ a │ b │ new_col │ my_sum │
676
+ ├───┼───┼───┼─────────┼────────┤
677
+ │ 0 │ 1 │ 2 │ 9 │ 0 │
678
+ │ 1 │ 3 │ 4 │ 8 │ 1 │
679
+ ╰───┴───┴───┴─────────┴────────╯
680
+ ```
681
+
682
+ To create complex masks, we have the `AND`
683
+
684
+ ```nu
685
+ ❯ $mask and $mask1
686
+ ╭───┬─────────╮
687
+ │ # │ and_0_0 │
688
+ ├───┼─────────┤
689
+ │ 0 │ false │
690
+ │ 1 │ true │
691
+ │ 2 │ false │
692
+ ╰───┴─────────╯
693
+ ```
694
+
695
+ and `OR` operations
696
+
697
+ ```nu
698
+ ❯ $mask or $mask1
699
+ ╭───┬────────╮
700
+ │ # │ or_0_0 │
701
+ ├───┼────────┤
702
+ │ 0 │ true │
703
+ │ 1 │ true │
704
+ │ 2 │ false │
705
+ ╰───┴────────╯
706
+ ```
707
+
708
+ We can also create a mask by checking if some values exist in other Series.
709
+ Using the first dataframe that we created we can do something like this
710
+
711
+ ```nu
712
+ ❯ let mask3 = ($df | dfr col first | dfr is-in [b c])
713
+ ❯ $mask3
714
+ ╭──────────┬──────────────────────────────────────��──────────────────────────────────────────────────────────╮
715
+ │ │ ╭───┬─────────┬──────────────╮ │
716
+ │ input │ │ # │ expr │ value │ │
717
+ │ │ ├───┼─────────┼──────────────┤ │
718
+ │ │ │ 0 │ column │ first │ │
719
+ │ │ │ 1 │ literal │ Series[list] │ │
720
+ │ │ ╰───┴─────────┴──────────────╯ │
721
+ │ function │ IsIn │
722
+ │ options │ FunctionOptions { collect_groups: ApplyFlat, input_wildcard_expansion: false, auto_explode: tru │
723
+ │ │ e, fmt_str: "", cast_to_supertypes: true, allow_rename: false, pass_name_to_apply: false } │
724
+ ╰──────────┴─────────────────────────────────────────────────────────────────────────────────────────────────╯
725
+ ```
726
+
727
+ and this new mask can be used to filter the dataframe
728
+
729
+ ```nu
730
+ ❯ $df | dfr filter-with $mask3
731
+ ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────────╮
732
+ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │
733
+ ├───┼───────┼───────┼─────────┼─────────┼───────┼────────┼───────┼────────┤
734
+ │ 0 │ 4 │ 14 │ 0.40 │ 3.00 │ b │ a │ c │ second │
735
+ │ 1 │ 0 │ 15 │ 0.50 │ 4.00 │ b │ a │ a │ third │
736
+ │ 2 │ 6 │ 16 │ 0.60 │ 5.00 │ b │ a │ a │ second │
737
+ │ 3 │ 7 │ 17 │ 0.70 │ 6.00 │ b │ c │ a │ third │
738
+ │ 4 │ 8 │ 18 │ 0.80 │ 7.00 │ c │ c │ b │ eight │
739
+ │ 5 │ 9 │ 19 │ 0.90 │ 8.00 │ c │ c │ b │ ninth │
740
+ │ 6 │ 0 │ 10 │ 0.00 │ 9.00 │ c │ c │ b │ ninth │
741
+ ╰───┴───────┴───────┴─────────┴─────────┴───────┴────────┴───────┴────────╯
742
+ ```
743
+
744
+ Another operation that can be done with masks is setting or replacing a value
745
+ from a series. For example, we can change the value in the column `first` where
746
+ the value is equal to `a`
747
+
748
+ ::: warning
749
+ This is example is not updated to recent Nushell versions.
750
+ :::
751
+
752
+ ```nu
753
+ ❯ $df | dfr get first | dfr set new --mask ($df.first =~ a)
754
+ ╭───┬────────╮
755
+ │ # │ string │
756
+ ├───┼────────┤
757
+ │ 0 │ new │
758
+ │ 1 │ new │
759
+ │ 2 │ new │
760
+ │ 3 │ b │
761
+ │ 4 │ b │
762
+ │ 5 │ b │
763
+ │ 6 │ b │
764
+ │ 7 │ c │
765
+ │ 8 │ c │
766
+ │ 9 │ c │
767
+ ╰───┴────────╯
768
+ ```
769
+
770
+ ## Series as indices
771
+
772
+ Series can be also used as a way of filtering a dataframe by using them as a
773
+ list of indices. For example, let's say that we want to get rows 1, 4, and 6
774
+ from our original dataframe. With that in mind, we can use the next command to
775
+ extract that information
776
+
777
+ ```nu
778
+ ❯ let indices = ([1 4 6] | dfr into-df)
779
+ ❯ $df | dfr take $indices
780
+ ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────────╮
781
+ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │
782
+ ├───┼───────┼───────┼─────────┼─────────┼───────┼────────┼───────┼────────┤
783
+ │ 0 │ 2 │ 12 │ 0.20 │ 1.00 │ a │ b │ c │ second │
784
+ │ 1 │ 0 │ 15 │ 0.50 │ 4.00 │ b │ a │ a │ third │
785
+ │ 2 │ 7 │ 17 │ 0.70 │ 6.00 │ b │ c │ a │ third │
786
+ ╰───┴───────┴───────┴─────────┴─────────┴───────┴────────┴───────┴────────╯
787
+ ```
788
+
789
+ The command [`dfr take`](/commands/docs/dfr_take.md) is very handy, especially if we mix it with other commands.
790
+ Let's say that we want to extract all rows for the first duplicated element for
791
+ column `first`. In order to do that, we can use the command `dfr arg-unique` as
792
+ shown in the next example
793
+
794
+ ```nu
795
+ ❯ let indices = ($df | dfr get first | dfr arg-unique)
796
+ ❯ $df | dfr take $indices
797
+ ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────────╮
798
+ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │
799
+ ├───┼───────┼───────┼─────────┼─────────┼───────┼────────┼───────┼────────┤
800
+ │ 0 │ 1 │ 11 │ 0.10 │ 1.00 │ a │ b │ c │ first │
801
+ │ 1 │ 4 │ 14 │ 0.40 │ 3.00 │ b │ a │ c │ second │
802
+ │ 2 │ 8 │ 18 │ 0.80 │ 7.00 │ c │ c │ b │ eight │
803
+ ╰───┴───────┴───────┴─────────┴─────────┴───────┴────────┴───────┴────────╯
804
+ ```
805
+
806
+ Or what if we want to create a new sorted dataframe using a column in specific.
807
+ We can use the `arg-sort` to accomplish that. In the next example we
808
+ can sort the dataframe by the column `word`
809
+
810
+ ::: tip
811
+ The same result could be accomplished using the command [`sort`](/commands/docs/sort.md)
812
+ :::
813
+
814
+ ```nu
815
+ ❯ let indices = ($df | dfr get word | dfr arg-sort)
816
+ ❯ $df | dfr take $indices
817
+ ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────────╮
818
+ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │
819
+ ├───┼───────┼───────┼─────────┼─────────┼───────┼────────┼───────┼────────┤
820
+ │ 0 │ 8 │ 18 │ 0.80 │ 7.00 │ c │ c │ b │ eight │
821
+ │ 1 │ 1 │ 11 │ 0.10 │ 1.00 │ a │ b │ c │ first │
822
+ │ 2 │ 9 │ 19 │ 0.90 │ 8.00 │ c │ c │ b │ ninth │
823
+ │ 3 │ 0 │ 10 │ 0.00 │ 9.00 │ c │ c │ b │ ninth │
824
+ │ 4 │ 2 │ 12 │ 0.20 │ 1.00 │ a │ b │ c │ second │
825
+ │ 5 │ 4 │ 14 │ 0.40 │ 3.00 │ b │ a │ c │ second │
826
+ │ 6 │ 6 │ 16 │ 0.60 │ 5.00 │ b │ a │ a │ second │
827
+ │ 7 │ 3 │ 13 │ 0.30 │ 2.00 │ a │ b │ c │ third │
828
+ │ 8 │ 0 │ 15 │ 0.50 │ 4.00 │ b │ a │ a │ third │
829
+ │ 9 │ 7 │ 17 │ 0.70 │ 6.00 │ b │ c │ a │ third │
830
+ ╰───┴───────┴───────┴─────────┴─────────┴───────┴────────┴───────┴────────╯
831
+ ```
832
+
833
+ And finally, we can create new Series by setting a new value in the marked
834
+ indices. Have a look at the next command
835
+
836
+ ```nu
837
+ ❯ let indices = ([0 2] | dfr into-df);
838
+ ❯ $df | dfr get int_1 | dfr set-with-idx 123 --indices $indices
839
+ ╭───┬───────╮
840
+ │ # │ int_1 │
841
+ ├───┼───────┤
842
+ │ 0 │ 123 │
843
+ │ 1 │ 2 │
844
+ │ 2 │ 123 │
845
+ │ 3 │ 4 │
846
+ │ 4 │ 0 │
847
+ │ 5 │ 6 │
848
+ │ 6 │ 7 │
849
+ │ 7 │ 8 │
850
+ │ 8 │ 9 │
851
+ │ 9 │ 0 │
852
+ ╰───┴───────╯
853
+ ```
854
+
855
+ ## Unique values
856
+
857
+ Another operation that can be done with `Series` is to search for unique values
858
+ in a list or column. Lets use again the first dataframe we created to test
859
+ these operations.
860
+
861
+ The first and most common operation that we have is `value_counts`. This
862
+ command calculates a count of the unique values that exist in a Series. For
863
+ example, we can use it to count how many occurrences we have in the column
864
+ `first`
865
+
866
+ ```nu
867
+ ❯ $df | dfr get first | dfr value-counts
868
+ ╭───┬─��─────┬────────╮
869
+ │ # │ first │ counts │
870
+ ├───┼───────┼────────┤
871
+ │ 0 │ b │ 4 │
872
+ │ 1 │ a │ 3 │
873
+ │ 2 │ c │ 3 │
874
+ ╰───┴───────┴────────╯
875
+ ```
876
+
877
+ As expected, the command returns a new dataframe that can be used to do more
878
+ queries.
879
+
880
+ Continuing with our exploration of `Series`, the next thing that we can do is
881
+ to only get the unique unique values from a series, like this
882
+
883
+ ```nu
884
+ ❯ $df | dfr get first | dfr unique
885
+ ╭───┬───────╮
886
+ │ # │ first │
887
+ ├───┼───────┤
888
+ │ 0 │ c │
889
+ │ 1 │ b │
890
+ │ 2 │ a │
891
+ ╰───┴───────╯
892
+ ```
893
+
894
+ Or we can get a mask that we can use to filter out the rows where data is
895
+ unique or duplicated. For example, we can select the rows for unique values
896
+ in column `word`
897
+
898
+ ```nu
899
+ ❯ $df | dfr filter-with ($df | dfr get word | dfr is-unique)
900
+ ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬───────╮
901
+ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │
902
+ ├───┼───────┼───────┼─────────┼─────────┼───────┼────────┼───────┼───────┤
903
+ │ 0 │ 1 │ 11 │ 0.10 │ 1.00 │ a │ b │ c │ first │
904
+ │ 1 │ 8 │ 18 │ 0.80 │ 7.00 │ c │ c │ b │ eight │
905
+ ╰───┴───────┴───────┴─────────┴─────────┴───────┴────────┴───────┴───────╯
906
+ ```
907
+
908
+ Or all the duplicated ones
909
+
910
+ ```nu
911
+ ❯ $df | dfr filter-with ($df | dfr get word | dfr is-duplicated)
912
+ ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────────╮
913
+ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │
914
+ ├───┼───────┼───────┼─────────┼─────────┼───────┼────────┼───────┼────────┤
915
+ │ 0 │ 2 │ 12 │ 0.20 │ 1.00 │ a │ b │ c │ second │
916
+ │ 1 │ 3 │ 13 │ 0.30 │ 2.00 │ a │ b │ c │ third │
917
+ │ 2 │ 4 │ 14 │ 0.40 │ 3.00 │ b │ a │ c │ second │
918
+ │ 3 │ 0 │ 15 │ 0.50 │ 4.00 │ b │ a │ a │ third │
919
+ │ 4 │ 6 │ 16 │ 0.60 │ 5.00 │ b │ a │ a │ second │
920
+ │ 5 │ 7 │ 17 │ 0.70 │ 6.00 │ b │ c │ a │ third │
921
+ │ 6 │ 9 │ 19 │ 0.90 │ 8.00 │ c │ c │ b │ ninth │
922
+ │ 7 │ 0 │ 10 │ 0.00 │ 9.00 │ c │ c │ b │ ninth │
923
+ ╰───┴───────┴───────┴─────────┴─────────┴───────┴────────┴───────┴────────╯
924
+ ```
925
+
926
+ ## Lazy Dataframes
927
+
928
+ Lazy dataframes are a way to query data by creating a logical plan. The
929
+ advantage of this approach is that the plan never gets evaluated until you need
930
+ to extract data. This way you could chain together aggregations, joins and
931
+ selections and collect the data once you are happy with the selected
932
+ operations.
933
+
934
+ Let's create a small example of a lazy dataframe
935
+
936
+ ```nu
937
+ ❯ let a = ([[a b]; [1 a] [2 b] [3 c] [4 d]] | dfr into-lazy)
938
+ ❯ $a
939
+ ╭────────────────┬─────────────────────────────────────────────────────────╮
940
+ │ plan │ DF ["a", "b"]; PROJECT */2 COLUMNS; SELECTION: "None" │
941
+ │ │ │
942
+ │ optimized_plan │ DF ["a", "b"]; PROJECT */2 COLUMNS; SELECTION: "None" │
943
+ │ │ │
944
+ ╰────────────────┴─────────────────────────────────────────────────────────╯
945
+ ```
946
+
947
+ As you can see, the resulting dataframe is not yet evaluated, it stays as a
948
+ set of instructions that can be done on the data. If you were to collect that
949
+ dataframe you would get the next result
950
+
951
+ ```nu
952
+ ❯ $a | dfr collect
953
+ ╭───┬───┬───╮
954
+ │ # │ a │ b │
955
+ ├───┼───┼───┤
956
+ │ 0 │ 1 │ a │
957
+ │ 1 │ 2 │ b │
958
+ │ 2 │ 3 │ c │
959
+ │ 3 │ 4 │ d │
960
+ ╰───┴───┴───╯
961
+ ```
962
+
963
+ as you can see, the collect command executes the plan and creates a nushell
964
+ table for you.
965
+
966
+ All dataframes operations should work with eager or lazy dataframes. They are
967
+ converted in the background for compatibility. However, to take advantage of
968
+ lazy operations if is recommended to only use lazy operations with lazy
969
+ dataframes.
970
+
971
+ To find all lazy dataframe operations you can use
972
+
973
+ ```nu
974
+ $nu.scope.commands | where category =~ lazyframe
975
+ ```
976
+
977
+ With your lazy frame defined we can start chaining operations on it. For
978
+ example this
979
+
980
+ ```nu
981
+ ❯ $a |
982
+ ∙ dfr reverse |
983
+ ∙ dfr with-column [
984
+ ∙ ((dfr col a) * 2 | dfr as double_a)
985
+ ∙ ((dfr col a) / 2 | dfr as half_a)
986
+ ∙ ] | dfr collect
987
+ ╭───┬───┬───┬──────────┬────────╮
988
+ │ # │ a │ b │ double_a │ half_a │
989
+ ├───┼───┼───┼──────────┼────────┤
990
+ │ 0 │ 4 │ d │ 8 │ 2 │
991
+ │ 1 │ 3 │ c │ 6 │ 1 │
992
+ │ 2 │ 2 │ b │ 4 │ 1 │
993
+ │ 3 │ 1 │ a │ 2 │ 0 │
994
+ ╰───┴───┴───┴──────────┴────────╯
995
+ ```
996
+
997
+ :::tip
998
+ You can use the line buffer editor to format your queries (`ctr + o`) easily
999
+ :::
1000
+
1001
+ This query uses the lazy reverse command to invert the dataframe and the
1002
+ `dfr with-column` command to create new two columns using `expressions`.
1003
+ An `expression` is used to define an operation that is executed on the lazy
1004
+ frame. When put together they create the whole set of instructions used by the
1005
+ lazy commands to query the data. To list all the commands that generate an
1006
+ expression you can use
1007
+
1008
+ ```nu
1009
+ scope commands | where category =~ expression
1010
+ ```
1011
+
1012
+ In our previous example, we use the `dfr col` command to indicate that column `a`
1013
+ will be multiplied by 2 and then it will be aliased to the name `double_a`.
1014
+ In some cases the use of the `dfr col` command can be inferred. For example,
1015
+ using the `dfr select` command we can use only a string
1016
+
1017
+ ```nu
1018
+ > $a | dfr select a | dfr collect
1019
+ ```
1020
+
1021
+ or the `dfr col` command
1022
+
1023
+ ```nu
1024
+ > $a | dfr select (dfr col a) | dfr collect
1025
+ ```
1026
+
1027
+ Let's try something more complicated and create aggregations from a lazy
1028
+ dataframe
1029
+
1030
+ ```nu
1031
+ ❯ let a = ( [[name value]; [one 1] [two 2] [one 1] [two 3]] | dfr into-lazy )
1032
+ ❯ $a |
1033
+ ∙ dfr group-by name |
1034
+ ∙ dfr agg [
1035
+ ∙ (dfr col value | dfr sum | dfr as sum)
1036
+ ∙ (dfr col value | dfr mean | dfr as mean)
1037
+ ∙ ] | dfr collect
1038
+ ╭───┬──────┬─────┬──────╮
1039
+ │ # │ name │ sum │ mean │
1040
+ ├───┼──────┼─────┼──────┤
1041
+ │ 0 │ two │ 5 │ 2.50 │
1042
+ │ 1 │ one │ 2 │ 1.00 │
1043
+ ╰───┴──────┴─────┴──────╯
1044
+ ```
1045
+
1046
+ And we could join on a lazy dataframe that hasn't being collected. Let's join
1047
+ the resulting group by to the original lazy frame
1048
+
1049
+ ```nu
1050
+ ❯ let a = ( [[name value]; [one 1] [two 2] [one 1] [two 3]] | dfr into-lazy )
1051
+ ❯ let group = ($a
1052
+ ∙ | dfr group-by name
1053
+ ∙ | dfr agg [
1054
+ ∙ (dfr col value | dfr sum | dfr as sum)
1055
+ ∙ (dfr col value | dfr mean | dfr as mean)
1056
+ ∙ ])
1057
+ ❯ $a | dfr join $group name name | dfr collect
1058
+ ╭───┬──────┬───────┬─────┬──────╮
1059
+ │ # │ name │ value │ sum │ mean │
1060
+ ├───┼──────┼───────┼─────┼──────┤
1061
+ │ 0 │ one │ 1 │ 2 │ 1.00 │
1062
+ │ 1 │ two │ 2 │ 5 │ 2.50 │
1063
+ │ 2 │ one │ 1 │ 2 │ 1.00 │
1064
+ │ 3 │ two │ 3 │ 5 │ 2.50 │
1065
+ ╰───┴──────┴───────┴─────┴──────╯
1066
+ ```
1067
+
1068
+ As you can see lazy frames are a powerful construct that will let you query
1069
+ data using a flexible syntax, resulting in blazing fast results.
1070
+
1071
+ ## Dataframe commands
1072
+
1073
+ So far we have seen quite a few operations that can be done using `DataFrame`s
1074
+ commands. However, the commands we have used so far are not all the commands
1075
+ available to work with data and be assured that there will be more as the
1076
+ feature becomes more stable.
1077
+
1078
+ The next list shows the available dataframe commands with their descriptions, and
1079
+ whenever possible, their analogous Nushell command.
1080
+
1081
+ ::: warning
1082
+ This list may be outdated. To get the up-to-date command list, see
1083
+ [Dataframe](/commands/categories/dataframe.md)
1084
+ [Lazyframe](/commands/categories/lazyframe.md) and
1085
+ [Dataframe Or Lazyframe](/commands/categories/dataframe_or_lazyframe.md)
1086
+ command categories.
1087
+ :::
1088
+
1089
+
1090
+ | Command Name | Applies To | Description | Nushell Equivalent |
1091
+ | --------------- | --------------------------- | -------------------------------------------------------------------------- | ----------------------------- |
1092
+ | aggregate | DataFrame, GroupBy, Series | Performs an aggregation operation on a dataframe, groupby or series object | math |
1093
+ | all-false | Series | Returns true if all values are false | |
1094
+ | all-true | Series | Returns true if all values are true | all |
1095
+ | arg-max | Series | Return index for max value in series | |
1096
+ | arg-min | Series | Return index for min value in series | |
1097
+ | arg-sort | Series | Returns indexes for a sorted series | |
1098
+ | arg-true | Series | Returns indexes where values are true | |
1099
+ | arg-unique | Series | Returns indexes for unique values | |
1100
+ | count-null | Series | Counts null values | |
1101
+ | count-unique | Series | Counts unique value | |
1102
+ | drop | DataFrame | Creates a new dataframe by dropping the selected columns | drop |
1103
+ | drop-duplicates | DataFrame | Drops duplicate values in dataframe | |
1104
+ | drop-nulls | DataFrame, Series | Drops null values in dataframe | |
1105
+ | dtypes | DataFrame | Show dataframe data types | |
1106
+ | filter-with | DataFrame | Filters dataframe using a mask as reference | |
1107
+ | first | DataFrame | Creates new dataframe with first rows | first |
1108
+ | get | DataFrame | Creates dataframe with the selected columns | get |
1109
+ | group-by | DataFrame | Creates a groupby object that can be used for other aggregations | group-by |
1110
+ | is-duplicated | Series | Creates mask indicating duplicated values | |
1111
+ | is-in | Series | Checks if elements from a series are contained in right series | in |
1112
+ | is-not-null | Series | Creates mask where value is not null | |
1113
+ | is-null | Series | Creates mask where value is null | `<column_name> == null` |
1114
+ | is-unique | Series | Creates mask indicating unique values | |
1115
+ | join | DataFrame | Joins a dataframe using columns as reference | |
1116
+ | last | DataFrame | Creates new dataframe with last rows | last |
1117
+ | ls-df | | Lists stored dataframes | |
1118
+ | melt | DataFrame | Unpivot a DataFrame from wide to long format | |
1119
+ | not | Series Inverts boolean mask | |
1120
+ | open | | Loads dataframe form csv file | open |
1121
+ | pivot | GroupBy | Performs a pivot operation on a groupby object | pivot |
1122
+ | rename | Dataframe, Series | Renames a series | rename |
1123
+ | sample | DataFrame | Create sample dataframe | |
1124
+ | select | DataFrame | Creates a new dataframe with the selected columns | select |
1125
+ | set | Series | Sets value where given mask is true | |
1126
+ | set-with-idx | Series | Sets value in the given index | |
1127
+ | shift | Series | Shifts the values by a given period | |
1128
+ | show | DataFrame | Converts a section of the dataframe to a Table or List value | |
1129
+ | slice | DataFrame | Creates new dataframe from a slice of rows | |
1130
+ | sort-by | DataFrame, Series | Creates new sorted dataframe or series | sort |
1131
+ | take | DataFrame, Series | Creates new dataframe using the given indices | |
1132
+ | to csv | DataFrame | Saves dataframe to csv file | to csv |
1133
+ | into df | | Converts a pipelined Table or List into Dataframe | |
1134
+ | dummies | DataFrame | Creates a new dataframe with dummy variables | |
1135
+ | to parquet | DataFrame | Saves dataframe to parquet file | |
1136
+ | unique | Series | Returns unique values from a series | uniq |
1137
+ | value-counts | Series | Returns a dataframe with the counts for unique values in series | |
1138
+ | where | DataFrame | Filter dataframe to match the condition | where |
1139
+ | with-column | DataFrame | Adds a series to the dataframe | `insert <column_name> <value> \| upsert <column_name> { <new_value> }` |
1140
+
1141
+ ## Future of Dataframes
1142
+
1143
+ We hope that by the end of this page you have a solid grasp of how to use the
1144
+ dataframe commands. As you can see they offer powerful operations that can
1145
+ help you process data faster and natively.
1146
+
1147
+ However, the future of these dataframes is still very experimental. New
1148
+ commands and tools that take advantage of these commands will be added as they
1149
+ mature.
1150
+
1151
+ Keep visiting this book in order to check the new things happening to
1152
+ dataframes and how they can help you process data faster and efficiently.
default_shell.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Default shell
2
+
3
+ ## Setting Nu as default shell on your terminal
4
+
5
+ | Terminal | Platform | Instructions |
6
+ | :--------------: | ------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
7
+ | GNOME Terminal | Linux & BSDs | Open `Edit > Preferences`. In the right-hand panel, select the `Command` tab, tick `Run a custom command instead of my shell`, and set `Custom command` to the path to Nu. |
8
+ | GNOME Console | Linux & BSDs | Type the command `gsettings set org.gnome.Console shell "['/usr/bin/nu']"` (replace `/usr/bin/nu` with the path to Nu). Equivalently, use [dconf Editor](https://apps.gnome.org/DconfEditor/) to edit the `/org/gnome/Console/shell` key. |
9
+ | Kitty | Linux & BSDs | Press `Ctrl`+`Shift`+`F2` to open `kitty.conf`. Go to `shell` variable, uncomment the line and replace the `.` with the path to Nu. |
10
+ | Konsole | Linux & BSDs | Open `Settings > Edit Current Profile`. Set `Command` to the path to Nu. |
11
+ | XFCE Terminal | Linux & BSDs | Open `Edit > Preferences`. Check `Run a custom command instead of my shell`, and set `Custom command` to the path to Nu. |
12
+ | Terminal.app | macOS | Open `Terminal > Preferences`. Ensure you are on the `Profiles` tab, which should be the default tab. In the right-hand panel, select the `Shell` tab. Tick `Run command`, put the path to Nu in the textbox, and untick `Run inside shell`. |
13
+ | iTerm2 | macOS | Open `iTerm > Preferences`. Select the `Profiles` tab. In the right-hand panel under `Command`, change the dropdown from `Login Shell` to `Custom Shell`, and put the path to Nu in the textbox. |
14
+ | Windows Terminal | Windows | Press `Ctrl`+`,` to open `Settings`. Go to `Add a new profile > New empty profile`. Fill in the 'Name' and enter path to Nu in the 'Command line' textbox. Go to `Startup` option and select Nu as the 'Default profile'. Hit `Save`. |
15
+
16
+ ## Setting Nu as login shell (Linux, BSD & macOS)
17
+
18
+ ::: warning
19
+ Nu is still in development and is not intended to be POSIX compliant.
20
+ Be aware that some programs on your system might assume that your login shell is [POSIX](https://en.wikipedia.org/wiki/POSIX) compatible.
21
+ Breaking that assumption can lead to unexpected issues.
22
+ :::
23
+
24
+ To set the login shell you can use the [`chsh`](https://linux.die.net/man/1/chsh) command.
25
+ Some Linux distributions have a list of valid shells located in `/etc/shells` and will disallow changing the shell until Nu is in the whitelist.
26
+ You may see an error similar to the one below if you haven't updated the `shells` file:
27
+
28
+ @[code](@snippets/installation/chsh_invalid_shell_error.sh)
29
+
30
+ You can add Nu to the list of allowed shells by appending your Nu binary to the `shells` file.
31
+ The path to add can be found with the command `which nu`, usually it is `$HOME/.cargo/bin/nu`.
design_notes.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Design Notes
2
+
3
+ This chapter intends to give more in-depth overview of certain aspects of Nushell's design. The topics are not necessary for a basic usage, but reading them will help you understand how Nushell works and why.
4
+
5
+ We intend to expand this chapter in the future. If there is some topic that you find confusing and hard to understand, let us know. It might be a good candidate for a page here.
6
+
7
+ [How Nushell Code Gets Run](how_nushell_code_gets_run.md) explains what happens when you run Nushell source code. It explains how Nushell is in many ways closer to classic compiled languages, like C or Rust, than to other shells and dynamic languages and hopefully clears some confusion that stems from that.
environment.md ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Environment
2
+
3
+ A common task in a shell is to control the environment that external applications will use. This is often done automatically, as the environment is packaged up and given to the external application as it launches. Sometimes, though, we want to have more precise control over what environment variables an application sees.
4
+
5
+ You can see the current environment variables in the $env variable:
6
+
7
+ ```nu
8
+ ~> $env | table -e
9
+ ╭──────────────────────────────────┬───────────────────────────────────────────╮
10
+ │ │ ╭──────┬────────────────────────────────╮ │
11
+ │ ENV_CONVERSIONS │ │ │ ╭─────────────┬──────────────╮ │ │
12
+ │ │ │ PATH │ │ from_string │ <Closure 32> │ │ │
13
+ │ │ │ │ │ to_string │ <Closure 34> │ │ │
14
+ │ │ │ │ ╰─────────────┴──────────────╯ │ │
15
+ │ │ │ │ ╭─────────────┬──────────────╮ │ │
16
+ │ │ │ Path │ │ from_string │ <Closure 36> │ │ │
17
+ │ │ │ │ │ to_string │ <Closure 38> │ │ │
18
+ │ │ │ │ ╰─────────────┴──────────────╯ │ │
19
+ │ │ ╰──────┴────────────────────────────────╯ │
20
+ │ HOME │ /Users/jelle │
21
+ │ LSCOLORS │ GxFxCxDxBxegedabagaced │
22
+ | ... | ... |
23
+ ╰──────────────────────────────────┴───────────────────────────────────────────╯
24
+ ```
25
+
26
+ In Nushell, environment variables can be any value and have any type. You can see the type of an env variable with the describe command, for example: `$env.PROMPT_COMMAND | describe`.
27
+
28
+ To send environment variables to external applications, the values will need to be converted to strings. See [Environment variable conversions](#environment-variable-conversions) on how this works.
29
+
30
+ The environment is initially created from the Nu [configuration files](configuration.md) and from the environment that Nu is run inside of.
31
+
32
+ ## Setting environment variables
33
+
34
+ There are several ways to set an environment variable:
35
+
36
+ ### $env.VAR assignment
37
+
38
+ Using the `$env.VAR = "val"` is the most straightforward method
39
+
40
+ ```nu
41
+ > $env.FOO = 'BAR'
42
+ ```
43
+
44
+ So, if you want to extend the Windows `Path` variable, for example, you could do that as follows.
45
+
46
+ ```nu
47
+ $env.Path = ($env.Path | prepend 'C:\path\you\want\to\add')
48
+ ```
49
+
50
+ Here we've prepended our folder to the existing folders in the Path, so it will have the highest priority.
51
+ If you want to give it the lowest priority instead, you can use the [`append`](/commands/docs/append.md) command.
52
+
53
+ ### [`load-env`](/commands/docs/load-env.md)
54
+
55
+ If you have more than one environment variable you'd like to set, you can use [`load-env`](/commands/docs/load-env.md) to create a table of name/value pairs and load multiple variables at the same time:
56
+
57
+ ```nu
58
+ > load-env { "BOB": "FOO", "JAY": "BAR" }
59
+ ```
60
+
61
+ ### One-shot environment variables
62
+
63
+ These are defined to be active only temporarily for a duration of executing a code block.
64
+ See [Single-use environment variables](environment.md#single-use-environment-variables) for details.
65
+
66
+ ### Calling a command defined with [`def --env`](/commands/docs/def.md)
67
+
68
+ See [Defining environment from custom commands](environment.md#defining-environment-from-custom-commands) for details.
69
+
70
+ ### Using module's exports
71
+
72
+ See [Modules](modules.md) for details.
73
+
74
+ ## Reading environment variables
75
+
76
+ Individual environment variables are fields of a record that is stored in the `$env` variable and can be read with `$env.VARIABLE`:
77
+
78
+ ```nu
79
+ > $env.FOO
80
+ BAR
81
+ ```
82
+
83
+ 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:
84
+ ```nu
85
+ > $env.FOO | describe
86
+ Error: nu::shell::column_not_found
87
+
88
+ × Cannot find column
89
+ ╭─[entry #1:1:1]
90
+ 1 │ $env.FOO
91
+ · ──┬─ ─┬─
92
+ · │ ╰── cannot find column 'FOO'
93
+ · ╰── value originates here
94
+ ╰────
95
+
96
+ > $env.FOO? | describe
97
+ nothing
98
+
99
+ > $env.FOO? | default "BAR"
100
+ BAR
101
+ ```
102
+
103
+ Alternatively, you can check for the presence of an environmental variable with `in`:
104
+
105
+ ```
106
+ > $env.FOO
107
+ BAR
108
+
109
+ > if "FOO" in $env {
110
+ > echo $env.FOO
111
+ > }
112
+ BAR
113
+ ```
114
+
115
+ ## Scoping
116
+
117
+ 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).
118
+
119
+ Here is a small example to demonstrate the environment scoping:
120
+
121
+ ```nu
122
+ > $env.FOO = "BAR"
123
+ > do {
124
+ $env.FOO = "BAZ"
125
+ $env.FOO == "BAZ"
126
+ }
127
+ true
128
+ > $env.FOO == "BAR"
129
+ true
130
+ ```
131
+
132
+ ## Changing directory
133
+
134
+ Common task in a shell is to change directory with the [`cd`](/commands/docs/cd.md) command.
135
+ In Nushell, calling [`cd`](/commands/docs/cd.md) is equivalent to setting the `PWD` environment variable.
136
+ Therefore, it follows the same rules as other environment variables (for example, scoping).
137
+
138
+ ## Single-use environment variables
139
+
140
+ A common shorthand to set an environment variable once is available, inspired by Bash and others:
141
+
142
+ ```nu
143
+ > FOO=BAR $env.FOO
144
+ BAR
145
+ ```
146
+
147
+ You can also use [`with-env`](/commands/docs/with-env.md) to do the same thing more explicitly:
148
+
149
+ ```nu
150
+ > with-env { FOO: BAR } { $env.FOO }
151
+ BAR
152
+ ```
153
+
154
+ The [`with-env`](/commands/docs/with-env.md) command will temporarily set the environment variable to the value given (here: the variable "FOO" is given the value "BAR"). Once this is done, the [block](types_of_data.md#blocks) will run with this new environment variable set.
155
+
156
+ ## Permanent environment variables
157
+
158
+ You can also set environment variables at startup so they are available for the duration of Nushell running.
159
+ To do this, set an environment variable inside [the Nu configuration file](configuration.md).
160
+ For example:
161
+
162
+ ```nu
163
+ # In config.nu
164
+ $env.FOO = 'BAR'
165
+ ```
166
+
167
+ ## Defining environment from custom commands
168
+
169
+ Due to the scoping rules, any environment variables defined inside a custom command will only exist inside the command's scope.
170
+ However, a command defined as [`def --env`](/commands/docs/def.md) instead of [`def`](/commands/docs/def.md) (it applies also to [`export def`](/commands/docs/export_def.md), see [Modules](modules.md)) will preserve the environment on the caller's side:
171
+
172
+ ```nu
173
+ > def --env foo [] {
174
+ $env.FOO = 'BAR'
175
+ }
176
+
177
+ > foo
178
+
179
+ > $env.FOO
180
+ BAR
181
+ ```
182
+
183
+ ## Environment variable conversions
184
+
185
+ You can set the `ENV_CONVERSIONS` environment variable to convert other environment variables between a string and a value.
186
+ For example, the [default environment config](https://github.com/nushell/nushell/blob/main/crates/nu-utils/src/sample_config/default_env.nu) includes conversion of PATH (and Path used on Windows) environment variables from a string to a list.
187
+ After both `env.nu` and `config.nu` are loaded, any existing environment variable specified inside `ENV_CONVERSIONS` will be translated according to its `from_string` field into a value of any type.
188
+ External tools require environment variables to be strings, therefore, any non-string environment variable needs to be converted first.
189
+ The conversion of value -> string is set by the `to_string` field of `ENV_CONVERSIONS` and is done every time an external command is run.
190
+
191
+ Let's illustrate the conversions with an example.
192
+ Put the following in your config.nu:
193
+
194
+ ```nu
195
+ $env.ENV_CONVERSIONS = {
196
+ # ... you might have Path and PATH already there, add:
197
+ FOO : {
198
+ from_string: { |s| $s | split row '-' }
199
+ to_string: { |v| $v | str join '-' }
200
+ }
201
+ }
202
+ ```
203
+
204
+ Now, within a Nushell instance:
205
+
206
+ ```nu
207
+ > with-env { FOO : 'a-b-c' } { nu } # runs Nushell with FOO env. var. set to 'a-b-c'
208
+
209
+ > $env.FOO
210
+ 0 a
211
+ 1 b
212
+ 2 c
213
+ ```
214
+
215
+ You can see the `$env.FOO` is now a list in a new Nushell instance with the updated config.
216
+ You can also test the conversion manually by
217
+
218
+ ```nu
219
+ > do $env.ENV_CONVERSIONS.FOO.from_string 'a-b-c'
220
+ ```
221
+
222
+ Now, to test the conversion list -> string, run:
223
+
224
+ ```nu
225
+ > nu -c '$env.FOO'
226
+ a-b-c
227
+ ```
228
+
229
+ Because `nu` is an external program, Nushell translated the `[ a b c ]` list according to `ENV_CONVERSIONS.FOO.to_string` and passed it to the `nu` process.
230
+ Running commands with `nu -c` does not load the config file, therefore the env conversion for `FOO` is missing and it is displayed as a plain string -- this way we can verify the translation was successful.
231
+ You can also run this step manually by `do $env.ENV_CONVERSIONS.FOO.to_string [a b c]`
232
+
233
+ _(Important! The environment conversion string -> value happens **after** the env.nu and config.nu are evaluated. All environment variables in env.nu and config.nu are still strings unless you set them manually to some other values.)_
234
+
235
+ ## Removing environment variables
236
+
237
+ You can remove an environment variable only if it was set in the current scope via [`hide-env`](/commands/docs/hide_env.md):
238
+
239
+ ```nu
240
+ > $env.FOO = 'BAR'
241
+ ...
242
+ > hide-env FOO
243
+ ```
244
+
245
+ The hiding is also scoped which both allows you to remove an environment variable temporarily and prevents you from modifying a parent environment from within a child scope:
246
+
247
+ ```nu
248
+ > $env.FOO = 'BAR'
249
+ > do {
250
+ hide-env FOO
251
+ # $env.FOO does not exist
252
+ }
253
+ > $env.FOO
254
+ BAR
255
+ ```
escaping.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Escaping to the system
2
+
3
+ Nu provides a set of commands that you can use across different OSes ("internal" commands), and having this consistency is helpful. Sometimes, though, you want to run an external command that has the same name as an internal Nu command. To run the external [`ls`](/commands/docs/ls.md) or [`date`](/commands/docs/date.md) command, for example, you use the caret (^) command. Escaping with the caret prefix calls the command that's in the user's PATH (e.g. `/bin/ls` instead of Nu's internal [`ls`](/commands/docs/ls.md) command).
4
+
5
+ Nu internal command:
6
+
7
+ ```nu
8
+ > ls
9
+ ```
10
+
11
+ Escape to external command:
12
+
13
+ ```nu
14
+ > ^ls
15
+ ```
16
+
17
+ ## Windows note
18
+
19
+ When running an external command on Windows, nushell [used to](https://www.nushell.sh/blog/2022-08-16-nushell-0_67.html#windows-cmd-exe-changes-rgwood) use [Cmd.exe](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/cmd) to run the command, as a number of common commands on Windows are actually shell builtins and not available as separate executables. [Coming from CMD.EXE](coming_from_cmd.md) contains a list of these commands and how to map them to nushell native concepts.
explore.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `explore`
2
+
3
+ Explore is a table pager, just like `less` but for table structured data.
4
+
5
+ ## Signature
6
+
7
+ `> explore --head --index --reverse --peek`
8
+
9
+ ### Parameters
10
+
11
+ - `--head {boolean}`: turn off column headers
12
+ - `--index`: show row indexes (by default it's not showed)
13
+ - `--reverse`: start from the last row
14
+ - `--peek`: returns a last used value, so it can be used in next pipelines
15
+
16
+ ## Get Started
17
+
18
+ ```nu
19
+ ls | explore -i
20
+ ```
21
+
22
+ ![explore-ls-png](https://user-images.githubusercontent.com/20165848/207849604-421312e3-537f-4b2e-b83e-f1f83f2a79d5.png)
23
+
24
+ So the main point of [`explore`](/commands/docs/explore.md) is `:table` (Which you see on the above screenshot).
25
+
26
+ You can interact with it via `<Left>`, `<Right>`, `<Up>`, `<Down>` _arrow keys_.
27
+
28
+ You can inspect a underlying values by entering into cursor mode. You can press either `<i>` or `<Enter>` to do so.
29
+ Then using _arrow keys_ you can choose a necessary cell.
30
+ And you'll be able to see it's underlying structure.
31
+
32
+ You can obtain more information about the various aspects of it by `:help`.
33
+
34
+ ## Commands
35
+
36
+ [`explore`](/commands/docs/explore.md) has a list of built in commands you can use. Commands are run through pressing `<:>` and then a command name.
37
+
38
+ To find out the comprehensive list of commands you can type `:help`.
39
+
40
+ ## Config
41
+
42
+ You can configure many things (including styles and colors), via config.
43
+ You can find an example configuration in [`default-config.nu`](https://github.com/nushell/nushell/blob/main/crates/nu-utils/src/sample_config/default_config.nu).
44
+
45
+ ## Examples
46
+
47
+ ### Peeking a value
48
+
49
+ ```nu
50
+ $nu | explore --peek
51
+ ```
52
+
53
+ ![explore-peek-gif](https://user-images.githubusercontent.com/20165848/207854897-35cb7b1d-7f7d-4ae2-9ec8-df19ac04ac99.gif)
54
+
55
+ ### `:try` command
56
+
57
+ There's an interactive environment which you can use to navigate through data using `nu`.
58
+
59
+ ![explore-try-gif](https://user-images.githubusercontent.com/20165848/208159049-0954c327-9cdf-4cb3-a6e9-e3ba86fde55c.gif)
60
+
61
+ #### Keeping the chosen value by `$nu`
62
+
63
+ Remember you can combine it with `--peek`.
64
+
65
+ ![explore-try-nu-gif](https://user-images.githubusercontent.com/20165848/208161203-96b51209-726d-449a-959a-48b205c6f55a.gif)
externs.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Externs
2
+
3
+ Calling external commands is a fundamental part of using Nushell as a shell (and often using Nushell as a language). There's a problem, though: Nushell can't help with finding errors in the call, completions, or syntax highlighting with external commands.
4
+
5
+ This is where `extern` comes in. The `extern` keyword allows you to write a full signature for the command that lives outside of Nushell so that you get all the benefits above. If you take a look at the default config, you'll notice that there are a few extern calls in there. Here's one of them:
6
+
7
+ ```nu
8
+ export extern "git push" [
9
+ remote?: string@"nu-complete git remotes", # the name of the remote
10
+ refspec?: string@"nu-complete git branches" # the branch / refspec
11
+ --verbose(-v) # be more verbose
12
+ --quiet(-q) # be more quiet
13
+ --repo: string # repository
14
+ --all # push all refs
15
+ --mirror # mirror all refs
16
+ --delete(-d) # delete refs
17
+ --tags # push tags (can't be used with --all or --mirror)
18
+ --dry-run(-n) # dry run
19
+ --porcelain # machine-readable output
20
+ --force(-f) # force updates
21
+ --force-with-lease: string # require old value of ref to be at this value
22
+ --recurse-submodules: string # control recursive pushing of submodules
23
+ --thin # use thin pack
24
+ --receive-pack: string # receive pack program
25
+ --exec: string # receive pack program
26
+ --set-upstream(-u) # set upstream for git pull/status
27
+ --progress # force progress reporting
28
+ --prune # prune locally removed refs
29
+ --no-verify # bypass pre-push hook
30
+ --follow-tags # push missing but relevant tags
31
+ --signed: string # GPG sign the push
32
+ --atomic # request atomic transaction on remote side
33
+ --push-option(-o): string # option to transmit
34
+ --ipv4(-4) # use IPv4 addresses only
35
+ --ipv6(-6) # use IPv6 addresses only
36
+ ]
37
+ ```
38
+
39
+ You'll notice this gives you all the same descriptive syntax that internal commands do, letting you describe flags, short flags, positional parameters, types, and more.
40
+
41
+ ::: warning Note
42
+ A Nushell comment that continues on the same line for argument documentation purposes requires a space before the ` #` pound sign.
43
+ :::
44
+
45
+ ## Types and custom completions
46
+
47
+ In the above example, you'll notice some types are followed by `@` followed by the name of a command. We talk more about [custom completions](custom_completions.md) in their own section.
48
+
49
+ Both the type (or shape) of the argument and the custom completion tell Nushell about how to complete values for that flag or position. For example, setting a shape to `path` allows Nushell to complete the value to a filepath for you. Using the `@` with a custom completion overrides this default behavior, letting the custom completion give you full completion list.
50
+
51
+ ## Format specifiers
52
+
53
+ Positional parameters can be made optional with a `?` (as seen above) the remaining parameters can be matched with `...` before the parameter name, which will return a list of arguments.
54
+
55
+ ```nu
56
+ export extern "git add" [
57
+ ...pathspecs: glob
58
+ # …
59
+ ]
60
+ ```
61
+
62
+ ## Limitations
63
+
64
+ There are a few limitations to the current `extern` syntax. In Nushell, flags and positional arguments are very flexible: flags can precede positional arguments, flags can be mixed into positional arguments, and flags can follow positional arguments. Many external commands are not this flexible. There is not yet a way to require a particular ordering of flags and positional arguments to the style required by the external.
65
+
66
+ The second limitation is that some externals require flags to be passed using `=` to separate the flag and the value. In Nushell, the `=` is a convenient optional syntax and there's currently no way to require its use.
getting_started.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Getting Started
2
+
3
+ Let's get started! :elephant:
4
+
5
+ First, to be able to use Nushell, we need to [install it](installation.md).
6
+
7
+ The next sections will give you a [short tour of Nushell by example](quick_tour.md) (including how to get help from within Nushell), and show you how to [move around your file system](moving_around.md).
8
+
9
+ Finally, because Nushell takes some design decisions that are quite different from typical shells or dynamic scripting languages, make sure to check [Thinking in Nu](thinking_in_nu.md) that explains some of these concepts.
hooks.md ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hooks
2
+
3
+ Hooks allow you to run a code snippet at some predefined situations.
4
+ They are only available in the interactive mode ([REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)), they do not work if you run a Nushell with a script (`nu script.nu`) or commands (`nu -c "print foo"`) arguments.
5
+
6
+ Currently, we support these types of hooks:
7
+
8
+ - `pre_prompt` : Triggered before the prompt is drawn
9
+ - `pre_execution` : Triggered before the line input starts executing
10
+ - `env_change` : Triggered when an environment variable changes
11
+ - `display_output` : A block that the output is passed to (experimental).
12
+ - `command_not_found` : Triggered when a command is not found.
13
+
14
+ To make it clearer, we can break down Nushell's execution cycle.
15
+ The steps to evaluate one line in the REPL mode are as follows:
16
+
17
+ 1. Check for `pre_prompt` hooks and run them
18
+ 1. Check for `env_change` hooks and run them
19
+ 1. Display prompt and wait for user input
20
+ 1. After user typed something and pressed "Enter": Check for `pre_execution` hooks and run them
21
+ 1. Parse and evaluate user input
22
+ 1. If a command is not found: Run the `command_not_found` hook. If it returns a string, show it.
23
+ 1. If `display_output` is defined, use it to print command output
24
+ 1. Return to 1.
25
+
26
+ ## Basic Hooks
27
+
28
+ To enable hooks, define them in your [config](configuration.md):
29
+
30
+ ```nu
31
+ $env.config = {
32
+ # ...other config...
33
+
34
+ hooks: {
35
+ pre_prompt: { print "pre prompt hook" }
36
+ pre_execution: { print "pre exec hook" }
37
+ env_change: {
38
+ PWD: {|before, after| print $"changing directory from ($before) to ($after)" }
39
+ }
40
+ }
41
+ }
42
+ ```
43
+
44
+ Try putting the above to your config, running Nushell and moving around your filesystem.
45
+ When you change a directory, the `PWD` environment variable changes and the change triggers the hook with the previous and the current values stored in `before` and `after` variables, respectively.
46
+
47
+ Instead of defining just a single hook per trigger, it is possible to define a **list of hooks** which will run in sequence:
48
+
49
+ ```nu
50
+ $env.config = {
51
+ ...other config...
52
+
53
+ hooks: {
54
+ pre_prompt: [
55
+ { print "pre prompt hook" }
56
+ { print "pre prompt hook2" }
57
+ ]
58
+ pre_execution: [
59
+ { print "pre exec hook" }
60
+ { print "pre exec hook2" }
61
+ ]
62
+ env_change: {
63
+ PWD: [
64
+ {|before, after| print $"changing directory from ($before) to ($after)" }
65
+ {|before, after| print $"changing directory from ($before) to ($after) 2" }
66
+ ]
67
+ }
68
+ }
69
+ }
70
+ ```
71
+
72
+ Also, it might be more practical to update the existing config with new hooks, instead of defining the whole config from scratch:
73
+
74
+ ```nu
75
+ $env.config = ($env.config | upsert hooks {
76
+ pre_prompt: ...
77
+ pre_execution: ...
78
+ env_change: {
79
+ PWD: ...
80
+ }
81
+ })
82
+ ```
83
+
84
+ ## Changing Environment
85
+
86
+ One feature of the hooks is that they preserve the environment.
87
+ Environment variables defined inside the hook **block** will be preserved in a similar way as [`def --env`](environment.md#defining-environment-from-custom-commands).
88
+ You can test it with the following example:
89
+
90
+ ```nu
91
+ > $env.config = ($env.config | upsert hooks {
92
+ pre_prompt: { $env.SPAM = "eggs" }
93
+ })
94
+
95
+ > $env.SPAM
96
+ eggs
97
+ ```
98
+
99
+ The hook blocks otherwise follow the general scoping rules, i.e., commands, aliases, etc. defined within the block will be thrown away once the block ends.
100
+
101
+ ## Conditional Hooks
102
+
103
+ One thing you might be tempted to do is to activate an environment whenever you enter a directory:
104
+
105
+ ```nu
106
+ $env.config = ($env.config | upsert hooks {
107
+ env_change: {
108
+ PWD: [
109
+ {|before, after|
110
+ if $after == /some/path/to/directory {
111
+ load-env { SPAM: eggs }
112
+ }
113
+ }
114
+ ]
115
+ }
116
+ })
117
+ ```
118
+
119
+ This won't work because the environment will be active only within the [`if`](/commands/docs/if.md) block.
120
+ In this case, you could easily rewrite it as `load-env (if $after == ... { ... } else { {} })` but this pattern is fairly common and later we'll see that not all cases can be rewritten like this.
121
+
122
+ To deal with the above problem, we introduce another way to define a hook -- **a record**:
123
+
124
+ ```nu
125
+ $env.config = ($env.config | upsert hooks {
126
+ env_change: {
127
+ PWD: [
128
+ {
129
+ condition: {|before, after| $after == /some/path/to/directory }
130
+ code: {|before, after| load-env { SPAM: eggs } }
131
+ }
132
+ ]
133
+ }
134
+ })
135
+ ```
136
+
137
+ When the hook triggers, it evaluates the `condition` block.
138
+ If it returns `true`, the `code` block will be evaluated.
139
+ If it returns `false`, nothing will happen.
140
+ If it returns something else, an error will be thrown.
141
+ The `condition` field can also be omitted altogether in which case the hook will always evaluate.
142
+
143
+ The `pre_prompt` and `pre_execution` hook types also support the conditional hooks but they don't accept the `before` and `after` parameters.
144
+
145
+ ## Hooks as Strings
146
+
147
+ So far a hook was defined as a block that preserves only the environment, but nothing else.
148
+ To be able to define commands or aliases, it is possible to define the `code` field as **a string**.
149
+ You can think of it as if you typed the string into the REPL and hit Enter.
150
+ So, the hook from the previous section can be also written as
151
+
152
+ ```nu
153
+ > $env.config = ($env.config | upsert hooks {
154
+ pre_prompt: '$env.SPAM = "eggs"'
155
+ })
156
+
157
+ > $env.SPAM
158
+ eggs
159
+ ```
160
+
161
+ This feature can be used, for example, to conditionally bring in definitions based on the current directory:
162
+
163
+ ```nu
164
+ $env.config = ($env.config | upsert hooks {
165
+ env_change: {
166
+ PWD: [
167
+ {
168
+ condition: {|_, after| $after == /some/path/to/directory }
169
+ code: 'def foo [] { print "foo" }'
170
+ }
171
+ {
172
+ condition: {|before, _| $before == /some/path/to/directory }
173
+ code: 'hide foo'
174
+ }
175
+ ]
176
+ }
177
+ })
178
+ ```
179
+
180
+ When defining a hook as a string, the `$before` and `$after` variables are set to the previous and current environment variable value, respectively, similarly to the previous examples:
181
+
182
+ ```nu
183
+ $env.config = ($env.config | upsert hooks {
184
+ env_change: {
185
+ PWD: {
186
+ code: 'print $"changing directory from ($before) to ($after)"'
187
+ }
188
+ }
189
+ }
190
+ ```
191
+
192
+ ## Examples
193
+
194
+ ### Adding a single hook to existing config
195
+
196
+ An example for PWD env change hook:
197
+
198
+ ```nu
199
+ $env.config = ($env.config | upsert hooks.env_change.PWD {|config|
200
+ let val = ($config | get -i hooks.env_change.PWD)
201
+
202
+ if $val == null {
203
+ $val | append {|before, after| print $"changing directory from ($before) to ($after)" }
204
+ } else {
205
+ [
206
+ {|before, after| print $"changing directory from ($before) to ($after)" }
207
+ ]
208
+ }
209
+ })
210
+ ```
211
+
212
+ ### Automatically activating an environment when entering a directory
213
+
214
+ This one looks for `test-env.nu` in a directory
215
+
216
+ ```nu
217
+ $env.config = ($env.config | upsert hooks.env_change.PWD {
218
+ [
219
+ {
220
+ condition: {|_, after|
221
+ ($after == '/path/to/target/dir'
222
+ and ($after | path join test-env.nu | path exists))
223
+ }
224
+ code: "overlay use test-env.nu"
225
+ }
226
+ {
227
+ condition: {|before, after|
228
+ ('/path/to/target/dir' not-in $after
229
+ and '/path/to/target/dir' in $before
230
+ and 'test-env' in (overlay list))
231
+ }
232
+ code: "overlay hide test-env --keep-env [ PWD ]"
233
+ }
234
+ ]
235
+ })
236
+ ```
237
+
238
+ ### Filtering or diverting command output
239
+
240
+ You can use the `display_output` hook to redirect the output of commands.
241
+ You should define a block that works on all value types.
242
+ The output of external commands is not filtered through `display_output`.
243
+
244
+ This hook can display the output in a separate window,
245
+ perhaps as rich HTML text. Here is the basic idea of how to do that:
246
+
247
+ ```nu
248
+ $env.config = ($env.config | upsert hooks {
249
+ display_output: { to html --partial --no-color | save --raw /tmp/nu-output.html }
250
+ })
251
+ ```
252
+
253
+ You can view the result by opening `file:///tmp/nu-output.html` in
254
+ a web browser.
255
+ Of course this isn't very convenient unless you use
256
+ a browser that automatically reloads when the file changes.
257
+ Instead of the [`save`](/commands/docs/save.md) command, you would normally customize this
258
+ to send the HTML output to a desired window.
259
+
260
+ ### Changing how output is displayed
261
+
262
+ You can change to default behavior of how output is displayed by using the `display_output` hook.
263
+ Here is an example that changes the default display behavior to show a table 1 layer deep if the terminal is wide enough, or collapse otherwise:
264
+
265
+ ```nu
266
+ $env.config = ($env.config | upsert hooks {
267
+ display_output: {if (term size).columns >= 100 { table -ed 1 } else { table }}
268
+ })
269
+ ```
270
+
271
+ ### `command_not_found` hook in _Arch Linux_
272
+
273
+ The following hook uses the `pkgfile` command, to find which packages commands belong to in _Arch Linux_.
274
+
275
+ ```nu
276
+ $env.config = {
277
+ ...other config...
278
+
279
+ hooks: {
280
+ ...other hooks...
281
+
282
+ command_not_found: {
283
+ |cmd_name| (
284
+ try {
285
+ let pkgs = (pkgfile --binaries --verbose $cmd_name)
286
+ if ($pkgs | is-empty) {
287
+ return null
288
+ }
289
+ (
290
+ $"(ansi $env.config.color_config.shape_external)($cmd_name)(ansi reset) " +
291
+ $"may be found in the following packages:\n($pkgs)"
292
+ )
293
+ }
294
+ )
295
+ }
296
+ }
297
+ }
298
+ ```
how_nushell_code_gets_run.md ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # How Nushell Code Gets Run
2
+
3
+ As you probably noticed, Nushell behaves quite differently from other shells and dynamic languages. In [Thinking in Nu](thinking_in_nu.md#think-of-nushell-as-a-compiled-language), we advise you to _think of Nushell as a compiled language_ but we do not give much insight into why. This section hopefully fills the gap.
4
+
5
+ First, let's give a few example which you might intuitively try but which do not work in Nushell.
6
+
7
+ 1. Sourcing a dynamic path (note that a constant would work, see [parse-time evaluation](#parse-time-evaluation))
8
+
9
+ ```nu
10
+ let my_path = 'foo'
11
+ source $"($my_path)/common.nu"
12
+ ```
13
+
14
+ 2. Write to a file and source it in a single script
15
+
16
+ ```nu
17
+ "def abc [] { 1 + 2 }" | save output.nu
18
+ source "output.nu"
19
+ ```
20
+
21
+ 3. Change a directory and source a path within (even though the file exists)
22
+
23
+ ```nu
24
+ if ('spam/foo.nu' | path exists) {
25
+ cd spam
26
+ source-env foo.nu
27
+ }
28
+ ```
29
+
30
+ The underlying reason why all of the above examples won't work is a strict separation of **parsing and evaluation** steps by **disallowing eval function**. In the rest of this section, we'll explain in detail what it means, why we're doing it, and what the implications are. The explanation aims to be as simple as possible, but it might help if you've written a program in some language before.
31
+
32
+ ## Parsing and Evaluation
33
+
34
+ ### Interpreted Languages
35
+
36
+ Let's start with a simple "hello world" Nushell program:
37
+
38
+ ```nu
39
+ # hello.nu
40
+
41
+ print "Hello world!"
42
+ ```
43
+
44
+ When you run `nu hello.nu`, Nushell's interpreter directly runs the program and prints the result to the screen. This is similar (on the highest level) to other languages that are typically interpreted, such as Python or Bash. If you write a similar "hello world" program in any of these languages and call `python hello.py` or `bash hello.bash`, the result will be printed to the screen. We can say that interpreters take the program in some representation (e.g., a source code), run it, and give you the result:
45
+
46
+ ```
47
+ source code --> interpreting --> result
48
+ ```
49
+
50
+ Under the hood, Nushell's interpreter is split into two parts, like this:
51
+
52
+ ```
53
+ 1. source code --> parsing --> Intermediate Representation (IR)
54
+ 2. IR --> evaluating --> result
55
+ ```
56
+
57
+ First, the source code is analyzed by the parser and converted into an intermediate representation (IR), which in Nushell's case are just some data structures. Then, these data structures are passed to the engine which evaluates them and produces the result. This is nothing unusual. For example, Python's source code is typically converted into [bytecode](https://en.wikipedia.org/wiki/Bytecode) before evaluation.
58
+
59
+ ### Compiled Languages
60
+
61
+ On the other side are languages that are typically "compiled", such as C, C++, or Rust. Assuming a simple ["hello world"](https://doc.rust-lang.org/stable/book/ch01-02-hello-world.html) in Rust
62
+
63
+ ```rust
64
+ // main.rs
65
+
66
+ fn main() {
67
+ println!("Hello, world!");
68
+ }
69
+ ```
70
+
71
+ you first need to _compile_ the program into [machine code instructions](https://en.wikipedia.org/wiki/Machine_code) and store the binary file to a disk (`rustc main.rs`). Then, to produce a result, you need to run the binary (`./main`), which passes the instructions to the CPU:
72
+
73
+ ```
74
+ 1. source code --> compiler --> machine code
75
+ 2. machine code --> CPU --> result
76
+ ```
77
+
78
+ You can see the compile-run sequence is not that much different from the parse-evaluate sequence of an interpreter. You begin with a source code, parse (or compile) it into some IR (or machine code), then evaluate (or run) the IR to get a result. You could think of machine code as just another type of IR and the CPU as its interpreter.
79
+
80
+ One big difference, however, between interpreted and compiled languages is that interpreted languages typically implement an _eval function_ while compiled languages do not. What does it mean?
81
+
82
+ ### Eval Function
83
+
84
+ Most languages considered as "dynamic" or "interpreted" have an eval function, for example Python (it has two, [eval](https://docs.python.org/3/library/functions.html#eval) and [exec](https://docs.python.org/3/library/functions.html#exec)) or [Bash](https://linux.die.net/man/1/bash). It is used to take source code and interpret it within a running interpreter. This can get a bit confusing, so let's give a Python example:
85
+
86
+ ```python
87
+ # hello_eval.py
88
+
89
+ print("Hello world!")
90
+ eval("print('Hello eval!')")
91
+ ```
92
+
93
+ When you run the file (`python hello_eval.py`), you'll see two messages: "Hello world!" and "Hello eval!". Here is what happened:
94
+
95
+ 1. Parse the whole source code
96
+ 2. Evaluate `print("Hello world!")`
97
+ 3. To evaluate `eval("print('Hello eval!')")`:
98
+ 3.1. Parse `print('Hello eval!')`
99
+ 3.2. Evaluate `print('Hello eval!')`
100
+
101
+ Of course, you can have more fun and try `eval("eval(\"print('Hello eval!')\")")` and so on...
102
+
103
+ You can see the eval function adds a new "meta" layer into the code execution. Instead of parsing the whole source code, then evaluating it, there is an extra parse-eval step during the evaluation. This means that the IR produced by the parser (whatever it is) can be further modified during the evaluation.
104
+
105
+ We've seen that without `eval`, the difference between compiled and interpreted languages is actually not that big. This is exactly what we mean by [thinking of Nushell as a compiled language](https://www.nushell.sh/book/thinking_in_nu.html#think-of-nushell-as-a-compiled-language): Despite Nushell being an interpreted language, its lack of `eval` gives it characteristics and limitations typical for traditional compiled languages like C or Rust. We'll dig deeper into what it means in the next section.
106
+
107
+ ## Implications
108
+
109
+ Consider this Python example:
110
+
111
+ ```python
112
+ exec("def hello(): print('Hello eval!')")
113
+ hello()
114
+ ```
115
+
116
+ _Note: We're using `exec` instead of `eval` because it can execute all valid Python code, not just expressions. The principle is similar, though._
117
+
118
+ What happens:
119
+
120
+ 1. Parse the whole source code
121
+ 2. To evaluate `exec("def hello(): print('Hello eval!')")`:
122
+ 2.1. Parse `def hello(): print('Hello eval!')`
123
+ 2.2 Evaluate `def hello(): print('Hello eval!')`
124
+ 3. Evaluate `hello()`
125
+
126
+ Note, that until step 2.2, the interpreter has no idea a function `hello` exists! This makes static analysis of dynamic languages challenging. In the example, the existence of `hello` function cannot be checked just by parsing (compiling) the source code. You actually need to go and evaluate (run) the code to find out. While in a compiled language, missing function is a guaranteed compile error, in a dynamic interpreted language, it is a runtime error (which can slip unnoticed if the line calling `hello()` is, for example, behind an `if` condition and does not get executed).
127
+
128
+ In Nushell, there are **exactly two steps**:
129
+
130
+ 1. Parse the whole source code
131
+ 2. Evaluate the whole source code
132
+
133
+ This is the complete parse-eval sequence.
134
+
135
+ Not having `eval`-like functionality prevents `eval`-related bugs from happening. Calling a non-existent function is 100% guaranteed parse-time error in Nushell. Furthermore, after the parse step, we have a deep insight into the program and we're 100% sure it is not going to change during evaluation. This trivially allows for powerful and reliable static analysis and IDE integration which is challenging to achieve with more dynamic languages. In general, you have more peace of mind when scaling Nushell programs to bigger applications.
136
+
137
+ _Before going into examples, one note about the "dynamic" and "static" terminology. Stuff that happens at runtime (during evaluation, after parsing) is considered "dynamic". Stuff that happens before running (during parsing / compilation) is called "static". Languages that have more stuff (such as `eval`, type checking, etc.) happening at runtime are sometimes called "dynamic". Languages that analyze most of the information (type checking, [data ownership](https://doc.rust-lang.org/stable/book/ch04-00-understanding-ownership.html), etc.) before evaluating the program are sometimes called "static". The whole debate can get quite confusing, but for the purpose of this text, the main difference between a "static" and "dynamic" language is whether it has or has not the eval function._
138
+
139
+ ## Common Mistakes
140
+
141
+ By insisting on strict parse-evaluation separation, we lose much of a flexibility users expect from dynamic interpreted languages, especially other shells, such as bash, fish, zsh and others. This leads to the examples at the beginning of this page not working. Let's break them down one by one
142
+
143
+ _Note: The following examples use [`source`](/commands/docs/source.md), but similar conclusions apply to other commands that parse Nushell source code, such as [`use`](/commands/docs/use.md), [`overlay use`](/commands/docs/overlay_use.md), [`hide`](/commands/docs/hide.md), [`register`](/commands/docs/register.md) or [`source-env`](/commands/docs/source-env.md)._
144
+
145
+ ### 1. Sourcing a dynamic path
146
+
147
+ ```nu
148
+ let my_path = 'foo'
149
+ source $"($my_path)/common.nu"
150
+ ```
151
+
152
+ Let's break down what would need to happen for this to work:
153
+
154
+ 1. Parse `let my_path = 'foo'` and `source $"($my_path)/config.nu"`
155
+ 2. To evaluate `source $"($my_path)/common.nu"`:
156
+ 1. Parse `$"($my_path)/common.nu"`
157
+ 2. Evaluate `$"($my_path)/common.nu"` to get the file name
158
+ 3. Parse the contents of the file
159
+ 4. Evaluate the contents of the file
160
+
161
+ You can see the process is similar to the `eval` functionality we talked about earlier. Nesting parse-evaluation cycles into the evaluation is not allowed in Nushell.
162
+
163
+ To give another perspective, here is why it is helpful to _think of Nushell as a compiled language_. Instead of
164
+
165
+ ```nu
166
+ let my_path = 'foo'
167
+ source $"($my_path)/common.nu"
168
+ ```
169
+
170
+ imagine it being written in some typical compiled language, such as C++
171
+
172
+ ```cpp
173
+ #include <string>
174
+
175
+ std::string my_path("foo");
176
+ #include <my_path + "/common.h">
177
+ ```
178
+
179
+ or Rust
180
+
181
+ ```rust
182
+ let my_path = "foo";
183
+ use format!("{}::common", my_path);
184
+ ```
185
+
186
+ If you've ever written a simple program in any of these languages, you can see these examples do not make a whole lot of sense. You need to have all the source code files ready and available to the compiler beforehand.
187
+
188
+ ### 2. Write to a file and source it in a single script
189
+
190
+ ```nu
191
+ "def abc [] { 1 + 2 }" | save output.nu
192
+ source "output.nu"
193
+ ```
194
+
195
+ Here, the sourced path is static (= known at parse-time) so everything should be fine, right? Well... no. Let's break down the sequence again:
196
+
197
+ 1. Parse the whole source code
198
+ 1. Parse `"def abc [] { 1 + 2 }" | save output.nu`
199
+ 2. Parse `source "output.nu"` - 1.2.1. Open `output.nu` and parse its contents
200
+ 2. Evaluate the whole source code
201
+ 1. Evaluate `"def abc [] { 1 + 2 }" | save output.nu` to generate `output.nu`
202
+ 2. ...wait what???
203
+
204
+ We're asking Nushell to read `output.nu` before it even exists. All the source code needs to be available to Nushell at parse-time, but `output.nu` is only generated during evaluation. Again, it helps here to _think of Nushell as a compiled language_.
205
+
206
+ ### 3. Change a directory and source a path within
207
+
208
+ (We assume the `spam/foo.nu` file exists.)
209
+
210
+ ```nu
211
+ if ('spam/foo.nu' | path exists) {
212
+ cd spam
213
+ source-env foo.nu
214
+ }
215
+ ```
216
+
217
+ This one is similar to the previous example. `cd spam` changes the directory _during evaluation_ but [`source-env`](/commands/docs/source-env.md) attempts to open and read `foo.nu` during parsing.
218
+
219
+ ## REPL
220
+
221
+ [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) is what happens when you run `nu` without any file. You launch an interactive prompt. By
222
+
223
+ ```nu
224
+ > some code...
225
+ ```
226
+
227
+ we denote a REPL entry followed by pressing Enter. For example
228
+
229
+ ```nu
230
+ > print "Hello world!"
231
+ Hello world!
232
+
233
+ > ls
234
+ # prints files and directories...
235
+ ```
236
+
237
+ means the following:
238
+
239
+ 1. Launch `nu`
240
+ 2. Type `print "Hello world!"`, press Enter
241
+ 3. Type [`ls`](/commands/docs/ls.md), press Enter
242
+
243
+ Hopefully, that's clear. Now, when you press Enter, these things happen:
244
+
245
+ 1. Parse the line input
246
+ 2. Evaluate the line input
247
+ 3. Merge the environment (such as the current working directory) to the internal Nushell state
248
+ 4. Wait for another input
249
+
250
+ In other words, each REPL invocation is its own separate parse-evaluation sequence. By merging the environment back to the Nushell's state, we maintain continuity between the REPL invocations.
251
+
252
+ To give an example, we showed that
253
+
254
+ ```nu
255
+ cd spam
256
+ source-env foo.nu
257
+ ```
258
+
259
+ does not work because the directory will be changed _after_ [`source-env`](/commands/docs/source-env.md) attempts to read the file. Running these commands as separate REPL entries, however, works:
260
+
261
+ ```nu
262
+ > cd spam
263
+
264
+ > source-env foo.nu
265
+ # yay, works!
266
+ ```
267
+
268
+ To see why, let's break down what happens in the example:
269
+
270
+ 1. Launch `nu`
271
+ 2. Parse `cd spam`
272
+ 3. Evaluate `cd spam`
273
+ 4. **Merge environment (including the current directory) into the Nushell state**
274
+ 5. Parse `source-env foo.nu`
275
+ 6. Evaluate `source-env foo.nu`
276
+ 7. Merge environment (including the current directory) into the Nushell state
277
+
278
+ When [`source-env`](/commands/docs/source-env.md) tries to open `foo.nu` during the parsing in step 5., it can do so because the directory change from step 3. was merged into the Nushell state in step 4. and therefore is visible in the following parse-evaluation cycles.
279
+
280
+ ### Parse-time Evaluation
281
+
282
+ While it is impossible to add parsing into the evaluation, we can add _a little bit_ of evaluation into parsing. This feature has been added [only recently](https://github.com/nushell/nushell/pull/7436) and we're going to expand it as needed.
283
+
284
+ One pattern that this unlocks is being able to [`source`](/commands/docs/source.md)/[`use`](/commands/docs/use.md)/etc. a path from a "variable". We've seen that
285
+
286
+ ```nu
287
+ let some_path = $nu.default-config-dir
288
+ source $"($some_path)/common.nu"
289
+ ```
290
+
291
+ does not work, but we can do the following:
292
+
293
+ ```nu
294
+ const some_path = $nu.default-config-dir
295
+ source $"($some_path)/config.nu"
296
+ ```
297
+
298
+ We can break down what is happening again:
299
+
300
+ 1. Parse the whole source code
301
+ 1. Parse `const some_path = $nu.default-config-dir`
302
+ 1. Evaluate\* `$nu.default-config-dir` to `/home/user/.config/nushell` and store it as a `some_path` constant
303
+ 2. Parse `source $"($some_path)/config.nu"`
304
+ 1. Evaluate\* `$some_path`, see that it is a constant, fetch it
305
+ 2. Evaluate\* `$"($some_path)/config.nu"` to `/home/user/.config/nushell/config.nu`
306
+ 3. Parse the `/home/user/.config/nushell/config.nu` file
307
+ 2. Evaluate the whole source code
308
+ 1. Evaluate `const some_path = $nu.default-config-dir` (i.e., add the `/home/user/.config/nushell` string to the runtime stack as `some_path` variable)
309
+ 2. Evaluate `source $"($some_path)/config.nu"` (i.e., evaluate the contents of `/home/user/.config/nushell/config.nu`)
310
+
311
+ This still does not violate our rule of not having an eval function, because an eval function adds additional parsing to the evaluation step. With parse-time evaluation we're doing the opposite.
312
+
313
+ Also, note the \* in steps 1.1.1. and 1.2.1. The evaluation happening during parsing is very restricted and limited to only a small subset of what is normally allowed during a regular evaluation. For example, the following is not allowed:
314
+
315
+ ```nu
316
+ const foo_contents = (open foo.nu)
317
+ ```
318
+
319
+ By allowing _everything_ during parse-time evaluation, we could set ourselves up to a lot of trouble (think of generating an infinite stream in a subexpression...). Generally, only a simple expressions _without side effects_ are allowed, such as string literals or integers, or composite types of these literals (records, lists, tables).
320
+
321
+ Compiled ("static") languages also tend to have a way to convey some logic at compile time, be it C's preprocessor, Rust's macros, or [Zig's comptime](https://kristoff.it/blog/what-is-zig-comptime). One reason is performance (if you can do it during compilation, you save the time during runtime) which is not as important for Nushell because we always do both parsing and evaluation, we do not store the parsed result anywhere (yet?). The second reason is similar to Nushell's: Dealing with limitations caused by the absence of the eval function.
322
+
323
+ ## Conclusion
324
+
325
+ Nushell operates in a scripting language space typically dominated by "dynamic" "interpreted" languages, such as Python, bash, zsh, fish, etc. While Nushell is also "interpreted" in a sense that it runs the code immediately, instead of storing the intermediate representation (IR) to a disk, one feature sets it apart from the pack: It does not have an **eval function**. In other words, Nushell cannot parse code and manipulate its IR during evaluation. This gives Nushell one characteristic typical for "static" "compiled" languages, such as C or Rust: All the source code must be visible to the parser beforehand, just like all the source code must be available to a C or Rust compiler. For example, you cannot [`source`](/commands/docs/source.md) or [`use`](/commands/docs/use.md) a path computed "dynamically" (during evaluation). This is surprising for users of more traditional scripting languages, but it helps to _think of Nushell as a compiled language_.
installation.md ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Installing Nu
2
+
3
+ There are lots of ways to get Nu up and running. You can download pre-built binaries from our [release page](https://github.com/nushell/nushell/releases), [use your favourite package manager](https://repology.org/project/nushell/versions), or build from source.
4
+
5
+ The main Nushell binary is named `nu` (or `nu.exe` on Windows). After installation, you can launch it by typing `nu`.
6
+
7
+ @[code](@snippets/installation/run_nu.sh)
8
+
9
+ ## Pre-built binaries
10
+
11
+ Nu binaries are published for Linux, macOS, and Windows [with each GitHub release](https://github.com/nushell/nushell/releases). Just download, extract the binaries, then copy them to a location on your PATH.
12
+
13
+ ## Package managers
14
+
15
+ Nu is available via several package managers:
16
+
17
+ [![Packaging status](https://repology.org/badge/vertical-allrepos/nushell.svg)](https://repology.org/project/nushell/versions)
18
+
19
+ For macOS and Linux, [Homebrew](https://brew.sh/) is a popular choice (`brew install nushell`).
20
+
21
+ For Windows:
22
+
23
+ - [Winget](https://docs.microsoft.com/en-us/windows/package-manager/winget/) (`winget install nushell`)
24
+ - [Chocolatey](https://chocolatey.org/) (`choco install nushell`)
25
+ - [Scoop](https://scoop.sh/) (`scoop install nu`)
26
+
27
+ Cross Platform installation:
28
+
29
+ - [npm](https://www.npmjs.com/) (`npm install -g nushell` Note that nu plugins are not included if you install in this way)
30
+
31
+ ## Build from source
32
+
33
+ You can also build Nu from source. First, you will need to set up the Rust toolchain and its dependencies.
34
+
35
+ ### Installing a compiler suite
36
+
37
+ For Rust to work properly, you'll need to have a compatible compiler suite installed on your system. These are the recommended compiler suites:
38
+
39
+ - Linux: GCC or Clang
40
+ - macOS: Clang (install Xcode)
41
+ - Windows: MSVC (install [Visual Studio](https://visualstudio.microsoft.com/vs/community/) or the [Visual Studio Build Tools](https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2022))
42
+ - Make sure to install the "Desktop development with C++" workload
43
+ - Any Visual Studio edition will work (Community is free)
44
+
45
+ ### Installing Rust
46
+
47
+ If you don't already have Rust on our system, the best way to install it is via [rustup](https://rustup.rs/). Rustup is a way of managing Rust installations, including managing using different Rust versions.
48
+
49
+ Nu currently requires the **latest stable (1.66.1 or later)** version of Rust. The best way is to let `rustup` find the correct version for you. When you first open `rustup` it will ask what version of Rust you wish to install:
50
+
51
+ @[code](@snippets/installation/rustup_choose_rust_version.sh)
52
+
53
+ Once you are ready, press 1 and then enter.
54
+
55
+ If you'd rather not install Rust via `rustup`, you can also install it via other methods (e.g. from a package in a Linux distro). Just be sure to install a version of Rust that is 1.66.1 or later.
56
+
57
+ ### Dependencies
58
+
59
+ #### Debian/Ubuntu
60
+
61
+ You will need to install the "pkg-config" and "libssl-dev" package:
62
+
63
+ @[code](@snippets/installation/install_pkg_config_libssl_dev.sh)
64
+
65
+ #### RHEL based distros
66
+
67
+ You will need to install "libxcb", "openssl-devel" and "libX11-devel":
68
+
69
+ @[code](@snippets/installation/install_rhel_dependencies.sh)
70
+
71
+ #### macOS
72
+
73
+ Using [Homebrew](https://brew.sh/), you will need to install "openssl" and "cmake" using:
74
+
75
+ @[code](@snippets/installation/macos_deps.sh)
76
+
77
+ ### Build using [crates.io](https://crates.io)
78
+
79
+ Nu releases are published as source to the popular Rust package registry [crates.io](https://crates.io/). This makes it easy to build and install the latest Nu release with `cargo`:
80
+
81
+ @[code](@snippets/installation/cargo_install_nu.sh)
82
+
83
+ That's it! The `cargo` tool will do the work of downloading Nu and its source dependencies, building it, and installing it into the cargo bin path.
84
+
85
+ If you want to install with support for [dataframes](dataframes.md), you can install using the `--features=dataframe` flag.
86
+
87
+ @[code](@snippets/installation/cargo_install_nu_more_features.sh)
88
+
89
+ ### Building from the GitHub repository
90
+
91
+ You can also build Nu from the latest source on GitHub. This gives you immediate access to the latest features and bug fixes. First, clone the repo:
92
+
93
+ @[code](@snippets/installation/git_clone_nu.sh)
94
+
95
+ From there, we can build and run Nu with:
96
+
97
+ @[code](@snippets/installation/build_nu_from_source.sh)
98
+
99
+ You can also build and run Nu in release mode, which enables more optimizations:
100
+
101
+ @[code](@snippets/installation/build_nu_from_source_release.sh)
102
+
103
+ People familiar with Rust may wonder why we do both a "build" and a "run" step if "run" does a build by default. This is to get around a shortcoming of the new `default-run` option in Cargo, and ensure that all plugins are built, though this may not be required in the future.
introduction.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Quick Tour
2
+
3
+ Nu takes cues from a lot of familiar territory: traditional shells like bash, object based shells like PowerShell, gradually typed languages like TypeScript, functional programming, systems programming, and more. But rather than trying to be a jack of all trades, Nu focuses its energy on doing a few things well:
4
+
5
+ - Being a flexible cross-platform shell with a modern feel
6
+ - Solving problems as a modern programming language that works with the structure of your data
7
+ - Giving clear error messages and clean IDE support
8
+
9
+ The easiest way to see what Nu can do is to start with some examples, so let's dive in.
10
+
11
+ The first thing you'll notice when you run a command like [`ls`](/commands/docs/ls.md) is that instead of a block of text coming back, you get a structured table.
12
+
13
+ @[code](@snippets/introduction/ls_example.sh)
14
+
15
+ The table is more than just showing the directory in a different way. Just like tables in a spreadsheet, this table allows us to work with the data more interactively.
16
+
17
+ The first thing we'll do is to sort our table by size. To do this, we'll take the output from [`ls`](/commands/docs/ls.md) and feed it into a command that can sort tables based on the contents of a column.
18
+
19
+ @[code](@snippets/introduction/ls_sort_by_reverse_example.sh)
20
+
21
+ You can see that to make this work we didn't pass commandline arguments to [`ls`](/commands/docs/ls.md). Instead, we used the [`sort-by`](/commands/docs/sort-by.md) command that Nu provides to do the sorting of the output of the [`ls`](/commands/docs/ls.md) command. To see the biggest files on top, we also used [`reverse`](/commands/docs/reverse.md).
22
+
23
+ Nu provides many commands that can work on tables. For example, we could filter the contents of the [`ls`](/commands/docs/ls.md) table so that it only shows files over 1 kilobyte:
24
+
25
+ @[code](@snippets/introduction/ls_where_example.sh)
26
+
27
+ Just as in the Unix philosophy, being able to have commands talk to each other gives us ways to mix-and-match in many different combinations. Let's look at a different command:
28
+
29
+ @[code](@snippets/introduction/ps_example.sh)
30
+
31
+ You may be familiar with the [`ps`](/commands/docs/ps.md) command if you've used Linux. With it, we can get a list of all the current processes that the system is running, what their status is, and what their name is. We can also see the CPU load for the processes.
32
+
33
+ What if we wanted to show the processes that were actively using the CPU? Just like we did with the [`ls`](/commands/docs/ls.md) command earlier, we can also work with the table that the [`ps`](/commands/docs/ps.md) command gives back to us:
34
+
35
+ @[code](@snippets/introduction/ps_where_example.sh)
36
+
37
+ So far, we've been using [`ls`](/commands/docs/ls.md) and [`ps`](/commands/docs/ps.md) to list files and processes. Nu also offers other commands that can create tables of useful information. Next, let's explore [`date`](/commands/docs/date.md) and [`sys`](/commands/docs/sys.md).
38
+
39
+ Running [`date now`](/commands/docs/date_now.md) gives us information about the current day and time:
40
+
41
+ @[code](@snippets/introduction/date_example.sh)
42
+
43
+ To get the date as a table we can feed it into [`date to-table`](/commands/docs/date_to-table.md)
44
+
45
+ @[code](@snippets/introduction/date_table_example.sh)
46
+
47
+ Running [`sys`](/commands/docs/sys.md) gives information about the system that Nu is running on:
48
+
49
+ @[code](@snippets/introduction/sys_example.sh)
50
+
51
+ This is a bit different than the tables we saw before. The [`sys`](/commands/docs/sys.md) command gives us a table that contains structured tables in the cells instead of simple values. To take a look at this data, we need to _get_ the column to view:
52
+
53
+ @[code](@snippets/introduction/sys_get_example.sh)
54
+
55
+ The [`get`](/commands/docs/get.md) command lets us jump into the contents of a column of the table. Here, we're looking into the "host" column, which contains information about the host that Nu is running on. The name of the OS, the hostname, the CPU, and more. Let's get the name of the users on the system:
56
+
57
+ @[code](@snippets/introduction/sys_get_nested_example.sh)
58
+
59
+ Right now, there's just one user on the system named "jt". You'll notice that we can pass a column path (the `host.sessions.name` part) and not just the name of the column. Nu will take the column path and go to the corresponding bit of data in the table.
60
+
61
+ You might have noticed something else that's different. Rather than having a table of data, we have just a single element: the string "jt". Nu works with both tables of data as well as strings. Strings are an important part of working with commands outside of Nu.
62
+
63
+ Let's see how strings work outside of Nu in action. We'll take our example from before and run the external [`echo`](/commands/docs/echo.md) command (the `^` tells Nu to not use the built-in [`echo`](/commands/docs/echo.md) command):
64
+
65
+ @[code](@snippets/introduction/sys_get_external_echo_example.sh)
66
+
67
+ If this looks very similar to what we had before, you have a keen eye! It is similar, but with one important difference: we've called `^echo` with the value we saw earlier. This allows us to pass data out of Nu into [`echo`](/commands/docs/echo.md) (or any command outside of Nu, like `git` for example).
68
+
69
+ ### Getting Help
70
+
71
+ Help text for any of Nu's built-in commands can be discovered with the [`help`](/commands/docs/help.md) command. To see all commands, run [`help commands`](/commands/docs/help_commands.md). You can also search for a topic by doing `help -f <topic>`.
72
+
73
+ @[code](@snippets/introduction/help_example.sh)
line_editor.md ADDED
@@ -0,0 +1,853 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reedline, Nu's line editor
2
+
3
+ Nushell's line editor [Reedline](https://github.com/nushell/reedline) is a
4
+ cross-platform line reader designed to be modular and flexible. The engine is
5
+ in charge of controlling the command history, validations, completions, hints
6
+ and screen paint.
7
+
8
+ ## Configuration
9
+
10
+ ### Editing mode
11
+
12
+ Reedline allows you to edit text using two modes: vi and emacs. If not
13
+ specified, the default edit mode is emacs mode. In order to select your
14
+ favorite you need to modify your config file and write down your preferred
15
+ mode.
16
+
17
+ For example:
18
+
19
+ ```nu
20
+ $env.config = {
21
+ ...
22
+ edit_mode: emacs
23
+ ...
24
+ }
25
+ ```
26
+
27
+ #### Default keybindings
28
+
29
+ Each edit mode comes with the usual keybinding for vi and emacs text editing.
30
+
31
+ Emacs and Vi Insert keybindings
32
+
33
+ | Key | Event |
34
+ | ----------- | --------------------- |
35
+ | Esc | Esc |
36
+ | Backspace | Backspace |
37
+ | End | Move to end of line |
38
+ | End | Complete history hint |
39
+ | Home | Move to line start |
40
+ | Ctr + c | Cancel current line |
41
+ | Ctr + l | Clear screen |
42
+ | Ctr + r | Search history |
43
+ | Ctr + Right | Complete history word |
44
+ | Ctr + Right | Move word right |
45
+ | Ctr + Left | Move word left |
46
+ | Up | Move menu up |
47
+ | Up | Move up |
48
+ | Down | Move menu down |
49
+ | Down | Move down |
50
+ | Left | Move menu left |
51
+ | Left | Move left |
52
+ | Right | History hint complete |
53
+ | Right | Move menu right |
54
+ | Right | Move right |
55
+ | Ctr + b | Move menu left |
56
+ | Ctr + b | Move left |
57
+ | Ctr + f | History hint complete |
58
+ | Ctr + f | Move menu right |
59
+ | Ctr + f | Move right |
60
+ | Ctr + p | Move menu up |
61
+ | Ctr + p | Move up |
62
+ | Ctr + n | Move menu down |
63
+ | Ctr + n | Move down |
64
+
65
+ Vi Normal keybindings
66
+
67
+ | Key | Event |
68
+ | ------- | ------------------- |
69
+ | Ctr + c | Cancel current line |
70
+ | Ctr + l | Clear screen |
71
+ | Up | Move menu up |
72
+ | Up | Move up |
73
+ | Down | Move menu down |
74
+ | Down | Move down |
75
+ | Left | Move menu left |
76
+ | Left | Move left |
77
+ | Right | Move menu right |
78
+ | Right | Move right |
79
+
80
+ Besides the previous keybindings, while in Vi normal mode you can use the classic
81
+ vi mode of executing actions by selecting a motion or an action. The available
82
+ options for the combinations are:
83
+
84
+ Vi Normal motions
85
+
86
+ | Key | motion |
87
+ | --- | ----------------- |
88
+ | w | Word |
89
+ | d | Line end |
90
+ | 0 | Line start |
91
+ | $ | Line end |
92
+ | f | Right until char |
93
+ | t | Right before char |
94
+ | F | Left until char |
95
+ | T | Left before char |
96
+
97
+ Vi Normal actions
98
+
99
+ | Key | action |
100
+ | --- | ------------------------------- |
101
+ | d | Delete |
102
+ | p | Paste after |
103
+ | P | Paste before |
104
+ | h | Move left |
105
+ | l | Move right |
106
+ | j | Move down |
107
+ | k | Move up |
108
+ | w | Move word right |
109
+ | b | Move word left |
110
+ | i | Enter Vi insert at current char |
111
+ | a | Enter Vi insert after char |
112
+ | 0 | Move to start of line |
113
+ | ^ | Move to start of line |
114
+ | $ | Move to end of line |
115
+ | u | Undo |
116
+ | c | Change |
117
+ | x | Delete char |
118
+ | s | History search |
119
+ | D | Delete to end |
120
+ | A | Append to end |
121
+
122
+ ### Command history
123
+
124
+ As mentioned before, Reedline manages and stores all the commands that are
125
+ edited and sent to Nushell. To configure the max number of records that
126
+ Reedline should store you will need to adjust this value in your config file:
127
+
128
+ ```nu
129
+ $env.config = {
130
+ ...
131
+ history: {
132
+ ...
133
+ max_size: 1000
134
+ ...
135
+ }
136
+ ...
137
+ }
138
+ ```
139
+
140
+ ### Customizing your prompt
141
+
142
+ Reedline prompt is also highly customizable. In order to construct your perfect
143
+ prompt, you could define the next environment variables in your config file:
144
+
145
+ ```nu
146
+ # Use nushell functions to define your right and left prompt
147
+ def create_left_prompt [] {
148
+ let path_segment = ($env.PWD)
149
+
150
+ $path_segment
151
+ }
152
+
153
+ def create_right_prompt [] {
154
+ let time_segment = ([
155
+ (date now | format date '%m/%d/%Y %r')
156
+ ] | str join)
157
+
158
+ $time_segment
159
+ }
160
+
161
+ $env.PROMPT_COMMAND = { create_left_prompt }
162
+ $env.PROMPT_COMMAND_RIGHT = { create_right_prompt }
163
+ ```
164
+
165
+ ::: tip
166
+ You don't have to define the environment variables using Nushell
167
+ functions. You can use simple strings to define them.
168
+ :::
169
+
170
+ You can also customize the prompt indicator for the line editor by modifying
171
+ the next env variables.
172
+
173
+ ```nu
174
+ $env.PROMPT_INDICATOR = "〉"
175
+ $env.PROMPT_INDICATOR_VI_INSERT = ": "
176
+ $env.PROMPT_INDICATOR_VI_NORMAL = "〉"
177
+ $env.PROMPT_MULTILINE_INDICATOR = "::: "
178
+ ```
179
+
180
+ ::: tip
181
+ The prompt indicators are environment variables that represent the
182
+ state of the prompt
183
+ :::
184
+
185
+ ## Keybindings
186
+
187
+ Reedline keybindings are powerful constructs that let you build chains of
188
+ events that can be triggered with a specific combination of keys.
189
+
190
+ For example, let's say that you would like to map the completion menu to the
191
+ `Ctrl + t` keybinding (default is `tab`). You can add the next entry to your
192
+ config file.
193
+
194
+ ```nu
195
+ $env.config = {
196
+ ...
197
+
198
+ keybindings: [
199
+ {
200
+ name: completion_menu
201
+ modifier: control
202
+ keycode: char_t
203
+ mode: emacs
204
+ event: { send: menu name: completion_menu }
205
+ }
206
+ ]
207
+
208
+ ...
209
+ }
210
+ ```
211
+
212
+ After loading this new `config.nu`, your new keybinding (`Ctrl + t`) will open
213
+ the completion command.
214
+
215
+ Each keybinding requires the next elements:
216
+
217
+ - name: Unique name for your keybinding for easy reference in `$config.keybindings`
218
+ - modifier: A key modifier for the keybinding. The options are:
219
+ - none
220
+ - control
221
+ - alt
222
+ - shift
223
+ - shift_alt
224
+ - alt_shift
225
+ - control_alt
226
+ - alt_control
227
+ - control_shift
228
+ - shift_control
229
+ - control_alt_shift
230
+ - control_shift_alt
231
+ - keycode: This represent the key to be pressed
232
+ - mode: emacs, vi_insert, vi_normal (a single string or a list. e.g.
233
+ [`vi_insert` `vi_normal`])
234
+ - event: The type of event that is going to be sent by the keybinding. The
235
+ options are:
236
+ - send
237
+ - edit
238
+ - until
239
+
240
+ ::: tip
241
+ All of the available modifiers, keycodes and events can be found with
242
+ the command [`keybindings list`](/commands/docs/keybindings_list.md)
243
+ :::
244
+
245
+ ::: tip
246
+ The keybindings added to `vi_insert` mode will be available when the
247
+ line editor is in insert mode (when you can write text), and the keybindings
248
+ marked with `vi_normal` mode will be available when in normal (when the cursor
249
+ moves using h, j, k or l)
250
+ :::
251
+
252
+ The event section of the keybinding entry is where the actions to be performed
253
+ are defined. In this field you can use either a record or a list of records.
254
+ Something like this
255
+
256
+ ```nu
257
+ ...
258
+ event: { send: Enter }
259
+ ...
260
+ ```
261
+
262
+ or
263
+
264
+ ```nu
265
+ ...
266
+ event: [
267
+ { edit: Clear }
268
+ { send: Enter }
269
+ ]
270
+ ...
271
+ ```
272
+
273
+ The first keybinding example shown in this page follows the first case; a
274
+ single event is sent to the engine.
275
+
276
+ The next keybinding is an example of a series of events sent to the engine. It
277
+ first clears the prompt, inserts a string and then enters that value
278
+
279
+ ```nu
280
+ $env.config = {
281
+ ...
282
+
283
+ keybindings: [
284
+ {
285
+ name: change_dir_with_fzf
286
+ modifier: CONTROL
287
+ keycode: Char_t
288
+ mode: emacs
289
+ event:[
290
+ { edit: Clear }
291
+ { edit: InsertString,
292
+ value: "cd (ls | where type == dir | each { |it| $it.name} | str join (char nl) | fzf | decode utf-8 | str trim)"
293
+
294
+ }
295
+ { send: Enter }
296
+ ]
297
+ }
298
+
299
+ ...
300
+ }
301
+ ```
302
+
303
+ One disadvantage of the previous keybinding is the fact that the inserted text
304
+ will be processed by the validator and saved in the history, making the
305
+ keybinding a bit slow and populating the command history with the same command.
306
+ For that reason there is the `executehostcommand` type of event. The next
307
+ example does the same as the previous one in a simpler way, sending a single
308
+ event to the engine
309
+
310
+ ```nu
311
+ $env.config = {
312
+ ...
313
+
314
+ keybindings: [
315
+ {
316
+ name: change_dir_with_fzf
317
+ modifier: CONTROL
318
+ keycode: Char_y
319
+ mode: emacs
320
+ event: {
321
+ send: executehostcommand,
322
+ cmd: "cd (ls | where type == dir | each { |it| $it.name} | str join (char nl) | fzf | decode utf-8 | str trim)"
323
+ }
324
+ }
325
+ ]
326
+
327
+ ...
328
+ }
329
+ ```
330
+
331
+ Before we continue you must have noticed that the syntax changes for edits and
332
+ sends, and for that reason it is important to explain them a bit more. A `send`
333
+ is all the `Reedline` events that can be processed by the engine and an `edit`
334
+ are all the `EditCommands` that can be processed by the engine.
335
+
336
+ ### Send type
337
+
338
+ To find all the available options for `send` you can use
339
+
340
+ ```nu
341
+ keybindings list | where type == events
342
+ ```
343
+
344
+ And the syntax for `send` events is the next one
345
+
346
+ ```nu
347
+ ...
348
+ event: { send: <NAME OF EVENT FROM LIST> }
349
+ ...
350
+ ```
351
+
352
+ ::: tip
353
+ You can write the name of the events with capital letters. The
354
+ keybinding parser is case insensitive
355
+ :::
356
+
357
+ There are two exceptions to this rule: the `Menu` and `ExecuteHostCommand`.
358
+ Those two events require an extra field to be complete. The `Menu` needs the
359
+ name of the menu to be activated (completion_menu or history_menu)
360
+
361
+ ```nu
362
+ ...
363
+ event: {
364
+ send: menu
365
+ name: completion_menu
366
+ }
367
+ ...
368
+ ```
369
+
370
+ and the `ExecuteHostCommand` requires a valid command that will be sent to the
371
+ engine
372
+
373
+ ```nu
374
+ ...
375
+ event: {
376
+ send: executehostcommand
377
+ cmd: "cd ~"
378
+ }
379
+ ...
380
+ ```
381
+
382
+ It is worth mentioning that in the events list you will also see `Edit([])`,
383
+ `Multiple([])` and `UntilFound([])`. These options are not available for the
384
+ parser since they are constructed based on the keybinding definition. For
385
+ example, a `Multiple([])` event is built for you when defining a list of
386
+ records in the keybinding's event. An `Edit([])` event is the same as the
387
+ `edit` type that was mentioned. And the `UntilFound([])` event is the same as
388
+ the `until` type mentioned before.
389
+
390
+ ### Edit type
391
+
392
+ The `edit` type is the simplification of the `Edit([])` event. The `event` type
393
+ simplifies defining complex editing events for the keybindings. To list the
394
+ available options you can use the next command
395
+
396
+ ```nu
397
+ keybindings list | where type == edits
398
+ ```
399
+
400
+ The usual syntax for an `edit` is the next one
401
+
402
+ ```nu
403
+ ...
404
+ event: { edit: <NAME OF EDIT FROM LIST> }
405
+ ...
406
+ ```
407
+
408
+ The syntax for the edits in the list that have a `()` changes a little bit.
409
+ Since those edits require an extra value to be fully defined. For example, if
410
+ we would like to insert a string where the prompt is located, then you will
411
+ have to use
412
+
413
+ ```nu
414
+ ...
415
+ event: {
416
+ edit: insertstring
417
+ value: "MY NEW STRING"
418
+ }
419
+ ...
420
+ ```
421
+
422
+ or say you want to move right until the first `S`
423
+
424
+ ```nu
425
+ ...
426
+ event: {
427
+ edit: moverightuntil
428
+ value: "S"
429
+ }
430
+ ...
431
+ ```
432
+
433
+ As you can see, these two types will allow you to construct any type of
434
+ keybinding that you require
435
+
436
+ ### Until type
437
+
438
+ To complete this keybinding tour we need to discuss the `until` type for event.
439
+ As you have seen so far, you can send a single event or a list of events. And
440
+ as we have seen, when a list of events is sent, each and every one of them is
441
+ processed.
442
+
443
+ However, there may be cases when you want to assign different events to the
444
+ same keybinding. This is especially useful with Nushell menus. For example, say
445
+ you still want to activate your completion menu with `Ctrl + t` but you also
446
+ want to move to the next element in the menu once it is activated using the
447
+ same keybinding.
448
+
449
+ For these cases, we have the `until` keyword. The events listed inside the
450
+ until event will be processed one by one with the difference that as soon as
451
+ one is successful, the event processing is stopped.
452
+
453
+ The next keybinding represents this case.
454
+
455
+ ```nu
456
+ $env.config = {
457
+ ...
458
+
459
+ keybindings: [
460
+ {
461
+ name: completion_menu
462
+ modifier: control
463
+ keycode: char_t
464
+ mode: emacs
465
+ event: {
466
+ until: [
467
+ { send: menu name: completion_menu }
468
+ { send: menunext }
469
+ ]
470
+ }
471
+ }
472
+ ]
473
+
474
+ ...
475
+ }
476
+ ```
477
+
478
+ The previous keybinding will first try to open a completion menu. If the menu
479
+ is not active, it will activate it and send a success signal. If the keybinding
480
+ is pressed again, since there is an active menu, then the next event it will
481
+ send is MenuNext, which means that it will move the selector to the next
482
+ element in the menu.
483
+
484
+ As you can see the `until` keyword allows us to define two events for the same
485
+ keybinding. At the moment of this writing, only the Menu events allow this type
486
+ of layering. The other non menu event types will always return a success value,
487
+ meaning that the `until` event will stop as soon as it reaches the command.
488
+
489
+ For example, the next keybinding will always send a `down` because that event
490
+ is always successful
491
+
492
+ ```nu
493
+ $env.config = {
494
+ ...
495
+
496
+ keybindings: [
497
+ {
498
+ name: completion_menu
499
+ modifier: control
500
+ keycode: char_t
501
+ mode: emacs
502
+ event: {
503
+ until: [
504
+ { send: down }
505
+ { send: menu name: completion_menu }
506
+ { send: menunext }
507
+ ]
508
+ }
509
+ }
510
+ ]
511
+
512
+ ...
513
+ }
514
+ ```
515
+
516
+ ### Removing a default keybinding
517
+
518
+ If you want to remove a certain default keybinding without replacing it with a different action, you can set `event: null`.
519
+
520
+ e.g. to disable screen clearing with `Ctrl + l` for all edit modes
521
+
522
+ ```nu
523
+ $env.config = {
524
+ ...
525
+
526
+ keybindings: [
527
+ {
528
+ modifier: control
529
+ keycode: char_l
530
+ mode: [emacs, vi_normal, vi_insert]
531
+ event: null
532
+ }
533
+ ]
534
+
535
+ ...
536
+ }
537
+
538
+ ```
539
+
540
+ ### Troubleshooting keybinding problems
541
+
542
+ Your terminal environment may not always propagate your key combinations on to nushell the way you expect it to.
543
+ You can use the command [`keybindings listen`](/commands/docs/keybindings_listen.md) to figure out if certain keypresses are actually received by nushell, and how.
544
+
545
+ ## Menus
546
+
547
+ Thanks to Reedline, Nushell has menus that can help you with your day to day
548
+ shell scripting. Next we present the default menus that are always available
549
+ when using Nushell
550
+
551
+ ### Help menu
552
+
553
+ The help menu is there to ease your transition into Nushell. Say you are
554
+ putting together an amazing pipeline and then you forgot the internal command
555
+ that would reverse a string for you. Instead of deleting your pipe, you can
556
+ activate the help menu with `F1`. Once active just type keywords for the
557
+ command you are looking for and the menu will show you commands that match your
558
+ input. The matching is done on the name of the commands or the commands
559
+ description.
560
+
561
+ To navigate the menu you can select the next element by using `tab`, you can
562
+ scroll the description by pressing left or right and you can even paste into
563
+ the line the available command examples.
564
+
565
+ The help menu can be configured by modifying the next parameters
566
+
567
+ ```nu
568
+ $env.config = {
569
+ ...
570
+
571
+ menus = [
572
+ ...
573
+ {
574
+ name: help_menu
575
+ only_buffer_difference: true # Search is done on the text written after activating the menu
576
+ marker: "? " # Indicator that appears with the menu is active
577
+ type: {
578
+ layout: description # Type of menu
579
+ columns: 4 # Number of columns where the options are displayed
580
+ col_width: 20 # Optional value. If missing all the screen width is used to calculate column width
581
+ col_padding: 2 # Padding between columns
582
+ selection_rows: 4 # Number of rows allowed to display found options
583
+ description_rows: 10 # Number of rows allowed to display command description
584
+ }
585
+ style: {
586
+ text: green # Text style
587
+ selected_text: green_reverse # Text style for selected option
588
+ description_text: yellow # Text style for description
589
+ }
590
+ }
591
+ ...
592
+ ]
593
+ ...
594
+ ```
595
+
596
+ ### Completion menu
597
+
598
+ The completion menu is a context sensitive menu that will present suggestions
599
+ based on the status of the prompt. These suggestions can range from path
600
+ suggestions to command alternatives. While writing a command, you can activate
601
+ the menu to see available flags for an internal command. Also, if you have
602
+ defined your custom completions for external commands, these will appear in the
603
+ menu as well.
604
+
605
+ The completion menu by default is accessed by pressing `tab` and it can be configured by
606
+ modifying these values from the config object:
607
+
608
+ ```nu
609
+ $env.config = {
610
+ ...
611
+
612
+ menus: [
613
+ ...
614
+ {
615
+ name: completion_menu
616
+ only_buffer_difference: false # Search is done on the text written after activating the menu
617
+ marker: "| " # Indicator that appears with the menu is active
618
+ type: {
619
+ layout: columnar # Type of menu
620
+ columns: 4 # Number of columns where the options are displayed
621
+ col_width: 20 # Optional value. If missing all the screen width is used to calculate column width
622
+ col_padding: 2 # Padding between columns
623
+ }
624
+ style: {
625
+ text: green # Text style
626
+ selected_text: green_reverse # Text style for selected option
627
+ description_text: yellow # Text style for description
628
+ }
629
+ }
630
+ ...
631
+ ]
632
+ ...
633
+ ```
634
+
635
+ By modifying these parameters you can customize the layout of your menu to your
636
+ liking.
637
+
638
+ ### History menu
639
+
640
+ The history menu is a handy way to access the editor history. When activating
641
+ the menu (default `Ctrl+r`) the command history is presented in reverse
642
+ chronological order, making it extremely easy to select a previous command.
643
+
644
+ The history menu can be configured by modifying these values from the config object:
645
+
646
+ ```nu
647
+ $env.config = {
648
+ ...
649
+
650
+ menus = [
651
+ ...
652
+ {
653
+ name: history_menu
654
+ only_buffer_difference: true # Search is done on the text written after activating the menu
655
+ marker: "? " # Indicator that appears with the menu is active
656
+ type: {
657
+ layout: list # Type of menu
658
+ page_size: 10 # Number of entries that will presented when activating the menu
659
+ }
660
+ style: {
661
+ text: green # Text style
662
+ selected_text: green_reverse # Text style for selected option
663
+ description_text: yellow # Text style for description
664
+ }
665
+ }
666
+ ...
667
+ ]
668
+ ...
669
+ ```
670
+
671
+ When the history menu is activated, it pulls `page_size` records from the
672
+ history and presents them in the menu. If there is space in the terminal, when
673
+ you press `Ctrl+x` again the menu will pull the same number of records and
674
+ append them to the current page. If it isn't possible to present all the pulled
675
+ records, the menu will create a new page. The pages can be navigated by
676
+ pressing `Ctrl+z` to go to previous page or `Ctrl+x` to go to next page.
677
+
678
+ #### Searching the history
679
+
680
+ To search in your history you can start typing key words for the command you
681
+ are looking for. Once the menu is activated, anything that you type will be
682
+ replaced by the selected command from your history. for example, say that you
683
+ have already typed this
684
+
685
+ ```nu
686
+ let a = ()
687
+ ```
688
+
689
+ you can place the cursor inside the `()` and activate the menu. You can filter
690
+ the history by typing key words and as soon as you select an entry, the typed
691
+ words will be replaced
692
+
693
+ ```nu
694
+ let a = (ls | where size > 10MiB)
695
+ ```
696
+
697
+ #### Menu quick selection
698
+
699
+ Another nice feature of the menu is the ability to quick select something from
700
+ it. Say you have activated your menu and it looks like this
701
+
702
+ ```nu
703
+ >
704
+ 0: ls | where size > 10MiB
705
+ 1: ls | where size > 20MiB
706
+ 2: ls | where size > 30MiB
707
+ 3: ls | where size > 40MiB
708
+ ```
709
+
710
+ Instead of pressing down to select the fourth entry, you can type `!3` and
711
+ press enter. This will insert the selected text in the prompt position, saving
712
+ you time scrolling down the menu.
713
+
714
+ History search and quick selection can be used together. You can activate the
715
+ menu, do a quick search, and then quick select using the quick selection
716
+ character.
717
+
718
+ ### User defined menus
719
+
720
+ In case you find that the default menus are not enough for you and you have
721
+ the need to create your own menu, Nushell can help you with that.
722
+
723
+ In order to add a new menu that fulfills your needs, you can use one of the default
724
+ layouts as a template. The templates available in nushell are columnar, list or
725
+ description.
726
+
727
+ The columnar menu will show you data in a columnar fashion adjusting the column
728
+ number based on the size of the text displayed in your columns.
729
+
730
+ The list type of menu will always display suggestions as a list, giving you the
731
+ option to select values using `!` plus number combination.
732
+
733
+ The description type will give you more space to display a description for some
734
+ values, together with extra information that could be inserted into the buffer.
735
+
736
+ Let's say we want to create a menu that displays all the variables created
737
+ during your session, we are going to call it `vars_menu`. This menu will use a
738
+ list layout (layout: list). To search for values, we want to use only the things
739
+ that are written after the menu has been activated (only_buffer_difference:
740
+ true).
741
+
742
+ With that in mind, the desired menu would look like this
743
+
744
+ ```nu
745
+ $env.config = {
746
+ ...
747
+
748
+ menus = [
749
+ ...
750
+ {
751
+ name: vars_menu
752
+ only_buffer_difference: true
753
+ marker: "# "
754
+ type: {
755
+ layout: list
756
+ page_size: 10
757
+ }
758
+ style: {
759
+ text: green
760
+ selected_text: green_reverse
761
+ description_text: yellow
762
+ }
763
+ source: { |buffer, position|
764
+ $nu.scope.vars
765
+ | where name =~ $buffer
766
+ | sort-by name
767
+ | each { |it| {value: $it.name description: $it.type} }
768
+ }
769
+ }
770
+ ...
771
+ ]
772
+ ...
773
+ ```
774
+
775
+ As you can see, the new menu is identical to the `history_menu` previously
776
+ described. The only huge difference is the new field called [`source`](/commands/docs/source.md). The
777
+ [`source`](/commands/docs/source.md) field is a nushell definition of the values you want to display in the
778
+ menu. For this menu we are extracting the data from `$nu.scope.vars` and we
779
+ are using it to create records that will be used to populate the menu.
780
+
781
+ The required structure for the record is the next one
782
+
783
+ ```nu
784
+ {
785
+ value: # The value that will be inserted in the buffer
786
+ description: # Optional. Description that will be display with the selected value
787
+ span: { # Optional. Span indicating what section of the string will be replaced by the value
788
+ start:
789
+ end:
790
+ }
791
+ extra: [string] # Optional. A list of strings that will be displayed with the selected value. Only works with a description menu
792
+ }
793
+ ```
794
+
795
+ For the menu to display something, at least the `value` field has to be present
796
+ in the resulting record.
797
+
798
+ In order to make the menu interactive, these two variables are available in
799
+ the block: `$buffer` and `$position`. The `$buffer` contains the value captured
800
+ by the menu, when the option `only_buffer_difference` is true, `$buffer` is the
801
+ text written after the menu was activated. If `only_buffer_difference` is
802
+ false, `$buffer` is all the string in line. The `$position` variable can be
803
+ used to create replacement spans based on the idea you had for your menu. The
804
+ value of `$position` changes based on whether `only_buffer_difference` is true
805
+ or false. When true, `$position` is the starting position in the string where
806
+ text was inserted after the menu was activated. When the value is false,
807
+ `$position` indicates the actual cursor position.
808
+
809
+ Using this information, you can design your menu to present the information you
810
+ require and to replace that value in the location you need it. The only thing
811
+ extra that you need to play with your menu is to define a keybinding that will
812
+ activate your brand new menu.
813
+
814
+ ### Menu keybindings
815
+
816
+ In case you want to change the default way both menus are activated, you can
817
+ change that by defining new keybindings. For example, the next two keybindings
818
+ assign the completion and history menu to `Ctrl+t` and `Ctrl+y` respectively
819
+
820
+ ```nu
821
+ $env.config = {
822
+ ...
823
+
824
+ keybindings: [
825
+ {
826
+ name: completion_menu
827
+ modifier: control
828
+ keycode: char_t
829
+ mode: [vi_insert vi_normal]
830
+ event: {
831
+ until: [
832
+ { send: menu name: completion_menu }
833
+ { send: menupagenext }
834
+ ]
835
+ }
836
+ }
837
+ {
838
+ name: history_menu
839
+ modifier: control
840
+ keycode: char_y
841
+ mode: [vi_insert vi_normal]
842
+ event: {
843
+ until: [
844
+ { send: menu name: history_menu }
845
+ { send: menupagenext }
846
+ ]
847
+ }
848
+ }
849
+ ]
850
+
851
+ ...
852
+ }
853
+ ```
loading_data.md ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Loading data
2
+
3
+ Earlier, we saw how you can use commands like [`ls`](/commands/docs/ls.md), [`ps`](/commands/docs/ps.md), [`date`](/commands/docs/date.md), and [`sys`](/commands/docs/sys.md) to load information about your files, processes, time of date, and the system itself. Each command gives us a table of information that we can explore. There are other ways we can load in a table of data to work with.
4
+
5
+ ## Opening files
6
+
7
+ One of Nu's most powerful assets in working with data is the [`open`](/commands/docs/open.md) command. It is a multi-tool that can work with a number of different data formats. To see what this means, let's try opening a json file:
8
+
9
+ @[code](@snippets/loading_data/vscode.sh)
10
+
11
+ In a similar way to [`ls`](/commands/docs/ls.md), opening a file type that Nu understands will give us back something that is more than just text (or a stream of bytes). Here we open a "package.json" file from a JavaScript project. Nu can recognize the JSON text and parse it to a table of data.
12
+
13
+ If we wanted to check the version of the project we were looking at, we can use the [`get`](/commands/docs/get.md) command.
14
+
15
+ ```nu
16
+ > open editors/vscode/package.json | get version
17
+ 1.0.0
18
+ ```
19
+
20
+ Nu currently supports the following formats for loading data directly into tables:
21
+
22
+ - csv
23
+ - eml
24
+ - ics
25
+ - ini
26
+ - json
27
+ - [nuon](#nuon)
28
+ - ods
29
+ - [SQLite databases](#sqlite)
30
+ - ssv
31
+ - toml
32
+ - tsv
33
+ - url
34
+ - vcf
35
+ - xlsx / xls
36
+ - xml
37
+ - yaml / yml
38
+
39
+ ::: tip Did you know?
40
+ Under the hood `open` will look for a `from ...` subcommand in your scope which matches the extension of your file.
41
+ You can thus simply extend the set of supported file types of `open` by creating your own `from ...` subcommand.
42
+ :::
43
+
44
+ But what happens if you load a text file that isn't one of these? Let's try it:
45
+
46
+ ```nu
47
+ > open README.md
48
+ ```
49
+
50
+ We're shown the contents of the file.
51
+
52
+ Below the surface, what Nu sees in these text files is one large string. Next, we'll talk about how to work with these strings to get the data we need out of them.
53
+
54
+ ## NUON
55
+
56
+ Nushell Object Notation (NUON) aims to be for Nushell what JavaScript Object Notation (JSON) is for JavaScript.
57
+ That is, NUON code is a valid Nushell code that describes some data structure.
58
+ For example, this is a valid NUON (example from the [default configuration file](https://github.com/nushell/nushell/blob/main/crates/nu-utils/src/sample_config/default_config.nu)):
59
+
60
+ ```nu
61
+ {
62
+ menus: [
63
+ # Configuration for default nushell menus
64
+ # Note the lack of source parameter
65
+ {
66
+ name: completion_menu
67
+ only_buffer_difference: false
68
+ marker: "| "
69
+ type: {
70
+ layout: columnar
71
+ columns: 4
72
+ col_width: 20 # Optional value. If missing all the screen width is used to calculate column width
73
+ col_padding: 2
74
+ }
75
+ style: {
76
+ text: green
77
+ selected_text: green_reverse
78
+ description_text: yellow
79
+ }
80
+ }
81
+ ]
82
+ }
83
+ ```
84
+
85
+ You might notice it is quite similar to JSON, and you're right.
86
+ **NUON is a superset of JSON!**
87
+ That is, any JSON code is a valid NUON code, therefore a valid Nushell code.
88
+ Compared to JSON, NUON is more "human-friendly".
89
+ For example, comments are allowed and commas are not required.
90
+
91
+ One limitation of NUON currently is that it cannot represent all of the Nushell [data types](types_of_data.md).
92
+ Most notably, NUON does not allow to serialize blocks.
93
+
94
+ ## Handling Strings
95
+
96
+ An important part of working with data coming from outside Nu is that it's not always in a format that Nu understands. Often this data is given to us as a string.
97
+
98
+ Let's imagine that we're given this data file:
99
+
100
+ ```nu
101
+ > open people.txt
102
+ Octavia | Butler | Writer
103
+ Bob | Ross | Painter
104
+ Antonio | Vivaldi | Composer
105
+ ```
106
+
107
+ Each bit of data we want is separated by the pipe ('|') symbol, and each person is on a separate line. Nu doesn't have a pipe-delimited file format by default, so we'll have to parse this ourselves.
108
+
109
+ The first thing we want to do when bringing in the file is to work with it a line at a time:
110
+
111
+ ```nu
112
+ > open people.txt | lines
113
+ ───┬──────────────────────────────
114
+ 0 │ Octavia | Butler | Writer
115
+ 1 │ Bob | Ross | Painter
116
+ 2 │ Antonio | Vivaldi | Composer
117
+ ───┴──────────────────────────────
118
+ ```
119
+
120
+ We can see that we're working with the lines because we're back into a list. Our next step is to see if we can split up the rows into something a little more useful. For that, we'll use the [`split`](/commands/docs/split.md) command. [`split`](/commands/docs/split.md), as the name implies, gives us a way to split a delimited string. We will use [`split`](/commands/docs/split.md)'s `column` subcommand to split the contents across multiple columns. We tell it what the delimiter is, and it does the rest:
121
+
122
+ ```nu
123
+ > open people.txt | lines | split column "|"
124
+ ───┬──────────┬───────────┬───────────
125
+ # │ column1 │ column2 │ column3
126
+ ───┼──────────┼───────────┼───────────
127
+ 0 │ Octavia │ Butler │ Writer
128
+ 1 │ Bob │ Ross │ Painter
129
+ 2 │ Antonio │ Vivaldi │ Composer
130
+ ───┴──────────┴───────────┴───────────
131
+ ```
132
+
133
+ That _almost_ looks correct. It looks like there's an extra space there. Let's [`trim`](/commands/docs/str_trim.md) that extra space:
134
+
135
+ ```nu
136
+ > open people.txt | lines | split column "|" | str trim
137
+ ───┬─────────┬─────────┬──────────
138
+ # │ column1 │ column2 │ column3
139
+ ───┼─────────┼─────────┼──────────
140
+ 0 │ Octavia │ Butler │ Writer
141
+ 1 │ Bob │ Ross │ Painter
142
+ 2 │ Antonio │ Vivaldi │ Composer
143
+ ───┴─────────┴─────────┴──────────
144
+ ```
145
+
146
+ Not bad. The [`split`](/commands/docs/split.md) command gives us data we can use. It also goes ahead and gives us default column names:
147
+
148
+ ```nu
149
+ > open people.txt | lines | split column "|" | str trim | get column1
150
+ ───┬─────────
151
+ 0 │ Octavia
152
+ 1 │ Bob
153
+ 2 │ Antonio
154
+ ───┴─────────
155
+ ```
156
+
157
+ We can also name our columns instead of using the default names:
158
+
159
+ ```nu
160
+ > open people.txt | lines | split column "|" first_name last_name job | str trim
161
+ ───┬────────────┬───────────┬──────────
162
+ # │ first_name │ last_name │ job
163
+ ───┼────────────┼───────────┼──────────
164
+ 0 │ Octavia │ Butler │ Writer
165
+ 1 │ Bob │ Ross │ Painter
166
+ 2 │ Antonio │ Vivaldi │ Composer
167
+ ───┴────────────┴───────────┴──────────
168
+ ```
169
+
170
+ Now that our data is in a table, we can use all the commands we've used on tables before:
171
+
172
+ ```nu
173
+ > open people.txt | lines | split column "|" first_name last_name job | str trim | sort-by first_name
174
+ ───┬────────────┬───────────┬──────────
175
+ # │ first_name │ last_name │ job
176
+ ───┼────────────┼───────────┼──────────
177
+ 0 │ Antonio │ Vivaldi │ Composer
178
+ 1 │ Bob │ Ross │ Painter
179
+ 2 │ Octavia │ Butler │ Writer
180
+ ───┴────────────┴───────────┴──────────
181
+ ```
182
+
183
+ There are other commands you can use to work with strings:
184
+
185
+ - [`str`](/commands/docs/str.md)
186
+ - [`lines`](/commands/docs/lines.md)
187
+ - [`size`](/commands/docs/size.md)
188
+
189
+ There is also a set of helper commands we can call if we know the data has a structure that Nu should be able to understand. For example, let's open a Rust lock file:
190
+
191
+ ```nu
192
+ > open Cargo.lock
193
+ # This file is automatically @generated by Cargo.
194
+ # It is not intended for manual editing.
195
+ [[package]]
196
+ name = "adhoc_derive"
197
+ version = "0.1.2"
198
+ ```
199
+
200
+ The "Cargo.lock" file is actually a .toml file, but the file extension isn't .toml. That's okay, we can use the [`from`](/commands/docs/from.md) command using the `toml` subcommand:
201
+
202
+ @[code](@snippets/loading_data/cargo-toml.sh)
203
+
204
+ The [`from`](/commands/docs/from.md) command can be used for each of the structured data text formats that Nu can open and understand by passing it the supported format as a subcommand.
205
+
206
+ ## Opening in raw mode
207
+
208
+ While it's helpful to be able to open a file and immediately work with a table of its data, this is not always what you want to do. To get to the underlying text, the [`open`](/commands/docs/open.md) command can take an optional `--raw` flag:
209
+
210
+ ```nu
211
+ > open Cargo.toml --raw
212
+ [package] name = "nu"
213
+ version = "0.1.3"
214
+ authors = ["Yehuda Katz <[email protected]>", "Jonathan Turner <[email protected]>"]
215
+ description = "A shell for the GitHub era"
216
+ license = "MIT"
217
+ ```
218
+
219
+ ## SQLite
220
+
221
+ SQLite databases are automatically detected by [`open`](/commands/docs/open.md), no matter what their file extension is. You can open a whole database:
222
+
223
+ ```nu
224
+ > open foo.db
225
+ ```
226
+
227
+ Or [`get`](/commands/docs/get.md) a specific table:
228
+
229
+ ```nu
230
+ > open foo.db | get some_table
231
+ ```
232
+
233
+ Or run any SQL query you like:
234
+
235
+ ```nu
236
+ > open foo.db | query db "select * from some_table"
237
+ ```
238
+
239
+ (Note: some older versions of Nu use `into db | query` instead of `query db` )
240
+
241
+ ## Fetching URLs
242
+
243
+ In addition to loading files from your filesystem, you can also load URLs by using the [`http get`](/commands/docs/http.md) command. This will fetch the contents of the URL from the internet and return it:
244
+
245
+ @[code](@snippets/loading_data/rust-lang-feed.sh)
metadata.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Metadata
2
+
3
+ In using Nu, you may have come across times where you felt like there was something extra going on behind the scenes. For example, let's say that you try to open a file that Nu supports only to forget and try to convert again:
4
+
5
+ ```nu
6
+ > open Cargo.toml | from toml
7
+ error: Expected a string from pipeline
8
+ - shell:1:18
9
+ 1 | open Cargo.toml | from toml
10
+ | ^^^^^^^^^ requires string input
11
+ - shell:1:5
12
+ 1 | open Cargo.toml | from toml
13
+ | ---------- object originates from here
14
+ ```
15
+
16
+ The error message tells us not only that what we gave [`from toml`](/commands/docs/from_toml.md) wasn't a string, but also where the value originally came from. How would it know that?
17
+
18
+ Values that flow through a pipeline in Nu often have a set of additional information, or metadata, attached to them. These are known as tags, like the tags on an item in a store. These tags don't affect the data, but they give Nu a way to improve the experience of working with that data.
19
+
20
+ Let's run the [`open`](/commands/docs/open.md) command again, but this time, we'll look at the tags it gives back:
21
+
22
+ ```nu
23
+ > metadata (open Cargo.toml)
24
+ ╭──────┬───────────────────╮
25
+ │ span │ {record 2 fields} │
26
+ ╰──────┴───────────────────╯
27
+ ```
28
+
29
+ Currently, we track only the span of where values come from. Let's take a closer look at that:
30
+
31
+ ```nu
32
+ > metadata (open Cargo.toml) | get span
33
+ ╭───────┬────────╮
34
+ │ start │ 212970 │
35
+ │ end │ 212987 │
36
+ ╰───────┴────────╯
37
+ ```
38
+
39
+ The span "start" and "end" here refer to where the underline will be in the line. If you count over 5, and then count up to 15, you'll see it lines up with the "Cargo.toml" filename. This is how the error we saw earlier knew what to underline.
modules.md ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modules
2
+
3
+ Similar to many other programming languages, Nushell also has modules to organize your code. Each module is a "bag" containing a bunch of definitions (typically commands) that you can export (take out of the bag) and use in your current scope. Since Nushell is also a shell, modules allow you to modify environment variables when importing them.
4
+
5
+ ## Quick Overview
6
+
7
+ There are three ways to define a module in Nushell:
8
+
9
+ 1. "inline"
10
+ - `module spam { ... }`
11
+ 2. from a file
12
+ - using a .nu file as a module
13
+ 3. from a directory
14
+ - directory must contain a `mod.nu` file
15
+
16
+ In Nushell, creating a module and importing definitions from a module are two different actions. The former is done using the `module` keyword. The latter using the `use` keyword. You can think of `module` as "wrapping definitions into a bag" and `use` as "opening a bag and taking definitions from it". In most cases, calling `use` will create the module implicitly, so you typically don't need to use `module` that much.
17
+
18
+ You can define the following things inside a module:
19
+
20
+ - Commands\* (`def`)
21
+ - Aliases (`alias`)
22
+ - Known externals\* (`extern`)
23
+ - Submodules (`module`)
24
+ - Imported symbols from other modules (`use`)
25
+ - Environment setup (`export-env`)
26
+
27
+ Only definitions marked with `export` are possible to access from outside of the module ("take out of the bag"). Definitions not marked with `export` are allowed but are visible only inside the module (you could call them private). (_`export-env` is special and does not require `export`._)
28
+
29
+ _\*These definitions can also be named `main` (see below)._
30
+
31
+ ## "Inline" modules
32
+
33
+ The simplest (and probably least useful) way to define a module is an "inline" module can be defined like this:
34
+
35
+ ```nu
36
+ module greetings {
37
+ export def hello [name: string] {
38
+ $"hello ($name)!"
39
+ }
40
+
41
+ export def hi [where: string] {
42
+ $"hi ($where)!"
43
+ }
44
+ }
45
+
46
+ use greetings hello
47
+
48
+ hello "world"
49
+ ```
50
+
51
+ _You can paste the code into a file and run it with `nu`, or type into the REPL._
52
+
53
+ First, we create a module (put `hello` and `hi` commands into a "bag" called `greetings`), then we import the `hello` command from the module (find a "bag" called `greetings` and take `hello` command from it) with `use`.
54
+
55
+ ## Modules from files
56
+
57
+ A .nu file can be a module. Just take the contents of the module block from the example above and save it to a file `greetings.nu`. The module name is automatically inferred as the stem of the file ("greetings").
58
+
59
+ ```nu
60
+ # greetings.nu
61
+
62
+ export def hello [name: string] {
63
+ $"hello ($name)!"
64
+ }
65
+
66
+ export def hi [where: string] {
67
+ $"hi ($where)!"
68
+ }
69
+ ```
70
+
71
+ then
72
+
73
+ ```nu
74
+ > use greetings.nu hello
75
+
76
+ > hello
77
+ ```
78
+
79
+ The result should be similar as in the previous section.
80
+
81
+ > **Note**
82
+ > that the `use greetings.nu hello` call here first implicitly creates the `greetings` module,
83
+ > then takes `hello` from it. You could also write it as `module greetings.nu`, `use greetings hello`.
84
+ > Using `module` can be useful if you're not interested in any definitions from the module but want to,
85
+ > e.g., re-export the module (`export module greetings.nu`).
86
+
87
+ ## Modules from directories
88
+
89
+ Finally, a directory can be imported as a module. The only condition is that it needs to contain a `mod.nu` file (even empty, which is not particularly useful, however). The `mod.nu` file defines the root module. Any submodules (`export module`) or re-exports (`export use`) must be declared inside the `mod.nu` file. We could write our `greetings` module like this:
90
+
91
+ _In the following examples, `/` is used at the end to denote that we're importing a directory but it is not required._
92
+
93
+ ```nu
94
+ # greetings/mod.nu
95
+
96
+ export def hello [name: string] {
97
+ $"hello ($name)!"
98
+ }
99
+
100
+ export def hi [where: string] {
101
+ $"hi ($where)!"
102
+ }
103
+ ```
104
+
105
+ then
106
+
107
+ ```nu
108
+ > use greetings/ hello
109
+
110
+ > hello
111
+ ```
112
+
113
+ The name of the module follows the same rule as module created from a file: Stem of the directory name, i.e., the directory name, is used as the module name. Again, you could do this as a two-step action using `module` and `use` separately, as explained in the previous section.
114
+
115
+ ::: tip
116
+ You can define `main` command inside `mod.nu` to create a command named after the module directory.
117
+ :::
118
+
119
+ ## Import Pattern
120
+
121
+ Anything after the [`use`](/commands/docs/use.md) keyword forms an **import pattern** which controls how the definitions are imported.
122
+ The import pattern has the following structure `use head members...` where `head` defines the module (name of an existing module, file, or directory). The members are optional and specify what exactly should be imported from the module.
123
+
124
+ Using our `greetings` example:
125
+
126
+ ```nu
127
+ use greetings
128
+ ```
129
+
130
+ imports all symbols prefixed with the `greetings` namespace (can call `greetings hello` and `greetings hi`).
131
+
132
+ ```nu
133
+ use greetings hello
134
+ ```
135
+
136
+ will import the `hello` command directly without any prefix.
137
+
138
+ ```nu
139
+ use greetings [hello, hi]
140
+ ```
141
+
142
+ imports multiple definitions<> directly without any prefix.
143
+
144
+ ```nu
145
+ use greetings *
146
+ ```
147
+
148
+ will import all names directly without any prefix.
149
+
150
+ ## `main`
151
+
152
+ Exporting a command called `main` from a module defines a command named as the module. Let's extend our `greetings` example:
153
+
154
+ ```nu
155
+ # greetings.nu
156
+
157
+ export def hello [name: string] {
158
+ $"hello ($name)!"
159
+ }
160
+
161
+ export def hi [where: string] {
162
+ $"hi ($where)!"
163
+ }
164
+
165
+ export def main [] {
166
+ "greetings and salutations!"
167
+ }
168
+ ```
169
+
170
+ then
171
+
172
+ ```nu
173
+ > use greetings.nu
174
+
175
+ > greetings
176
+ greetings and salutations!
177
+
178
+ > greetings hello world
179
+ hello world!
180
+ ```
181
+
182
+ The `main` is exported only when
183
+
184
+ - no import pattern members are used (`use greetings.nu`)
185
+ - glob member is used (`use greetings.nu *`)
186
+
187
+ Importing definitions selectively (`use greetings.nu hello` or `use greetings.nu [hello hi]`) does not define the `greetings` command from `main`. You can, however, selectively import `main` using `use greetings main` (or `[main]`) which defines _only_ the `greetings` command without pulling in `hello` or `hi`.
188
+
189
+ Apart from commands (`def`, `def --env`), known externals (`extern`) can also be named `main`.
190
+
191
+ ## Submodules and subcommands
192
+
193
+ Submodules are modules inside modules. They are automatically created when you call `use` on a directory: Any .nu files inside the directory are implicitly added as submodules of the main module. There are two more ways to add a submodule to a module:
194
+
195
+ 1. Using `export module`
196
+ 2. Using `export use`
197
+
198
+ The difference is that `export module some-module` _only_ adds the module as a submodule, while `export use some-module` _also_ re-exports the submodule's definitions. Since definitions of submodules are available when importing from a module, `export use some-module` is typically redundant, unless you want to re-export its definitions without the namespace prefix.
199
+
200
+ > **Note**
201
+ > `module` without `export` defines only a local module, it does not export a submodule.
202
+
203
+ Let's illustrate this with an example. Assume three files:
204
+
205
+ ```nu
206
+ # greetings.nu
207
+
208
+ export def hello [name: string] {
209
+ $"hello ($name)!"
210
+ }
211
+
212
+ export def hi [where: string] {
213
+ $"hi ($where)!"
214
+ }
215
+
216
+ export def main [] {
217
+ "greetings and salutations!"
218
+ }
219
+ ```
220
+
221
+ ```nu
222
+ # animals.nu
223
+
224
+ export def dog [] {
225
+ "haf"
226
+ }
227
+
228
+ export def cat [] {
229
+ "meow"
230
+ }
231
+ ```
232
+
233
+ ```nu
234
+ # voice.nu
235
+
236
+ export use greetings.nu *
237
+
238
+ export module animals.nu
239
+
240
+ ```
241
+
242
+ Then:
243
+
244
+ ```nu
245
+ > use voice.nu
246
+
247
+ > voice animals dog
248
+ haf
249
+
250
+ > voice animals cat
251
+ meow
252
+
253
+ > voice hello world
254
+ hello world
255
+
256
+ > voice hi there
257
+ hi there!
258
+
259
+ > voice greetings
260
+ greetings and salutations!
261
+
262
+ ```
263
+
264
+ As you can see, defining the submodule structure also shapes the command line API. In Nushell, namespaces directly folds into subcommands. This is true for all definitions: aliases, commands, known externals, modules.
265
+
266
+ ## Environment Variables
267
+
268
+ Modules can also define an environment using [`export-env`](/commands/docs/export-env.md):
269
+
270
+ ```nu
271
+ # greetings.nu
272
+
273
+ export-env {
274
+ $env.MYNAME = "Arthur, King of the Britons"
275
+ }
276
+
277
+ export def hello [] {
278
+ $"hello ($env.MYNAME)"
279
+ }
280
+ ```
281
+
282
+ When [`use`](/commands/docs/use.md) is evaluated, it will run the code inside the [`export-env`](/commands/docs/export-env.md) block and merge its environment into the current scope:
283
+
284
+ ```nu
285
+ > use greetings.nu
286
+
287
+ > $env.MYNAME
288
+ Arthur, King of the Britons
289
+
290
+ > greetings hello
291
+ hello Arthur, King of the Britons!
292
+ ```
293
+
294
+ ::: tip
295
+ You can put a complex code defining your environment without polluting the namespace of the module, for example:
296
+
297
+ ```nu
298
+ def tmp [] { "tmp" }
299
+ def other [] { "other" }
300
+
301
+ let len = (tmp | str length)
302
+
303
+ load-env {
304
+ OTHER_ENV: (other)
305
+ TMP_LEN: $len
306
+ }
307
+ }
308
+ ```
309
+
310
+ Only `$env.TMP_LEN` and `$env.OTHER_ENV` are preserved after evaluating the `export-env` module.
311
+ :::
312
+
313
+ ## Caveats
314
+
315
+ Like any programming language, Nushell is also a product of a tradeoff and there are limitations to our module system.
316
+
317
+ ### `export-env` runs only when the `use` call is _evaluated_
318
+
319
+ If you also want to keep your variables in separate modules and export their environment, you could try to [`export use`](/commands/docs/export_use.md) it:
320
+
321
+ ```nu
322
+ # purpose.nu
323
+ export-env {
324
+ $env.MYPURPOSE = "to build an empire."
325
+ }
326
+
327
+ export def greeting_purpose [] {
328
+ $"Hello ($env.MYNAME). My purpose is ($env.MYPURPOSE)"
329
+ }
330
+ ```
331
+
332
+ and then use it
333
+
334
+ ```nu
335
+ > use purpose.nu
336
+
337
+ > purpose greeting_purpose
338
+ ```
339
+
340
+ However, this won't work, because the code inside the module is not _evaluated_, only _parsed_ (only the `export-env` block is evaluated when you call `use purpose.nu`). To export the environment of `greetings.nu`, you need to add it to the `export-env` module:
341
+
342
+ ```nu
343
+ # purpose.nu
344
+ export-env {
345
+ use greetings.nu
346
+ $env.MYPURPOSE = "to build an empire."
347
+ }
348
+
349
+ export def greeting_purpose [] {
350
+ $"Hello ($env.MYNAME). My purpose is ($env.MYPURPOSE)"
351
+ }
352
+ ```
353
+
354
+ then
355
+
356
+ ```nu
357
+ > use purpose.nu
358
+
359
+ > purpose greeting_purpose
360
+ Hello Arthur, King of the Britons. My purpose is to build an empire.
361
+ ```
362
+
363
+ Calling `use purpose.nu` ran the `export-env` block inside `purpose.nu` which in turn ran `use greetings.nu` which in turn ran the `export-env` block inside `greetings.nu`, preserving the environment changes.
364
+
365
+ ### Module file / command cannot be named after parent module
366
+
367
+ - Module directory cannot contain .nu file named after the directory (`spam/spam.nu`)
368
+ - Consider a `spam` directory containing both `spam.nu` and `mod.nu`, calling `use spam *` would create an ambiguous situation where the `spam` module would be defined twice.
369
+ - Module cannot contain file named after the module
370
+ - Same case as above: Module `spam` containing both `main` and `spam` commands would create an ambiguous situation when exported as `use spam *`.
371
+
372
+ ## Examples
373
+
374
+ This section describes some useful patterns using modules.
375
+
376
+ ### Local Definitions
377
+
378
+ Anything defined in a module without the [`export`](/commands/docs/export.md) keyword will work only in the module's scope.
379
+
380
+ ```nu
381
+ # greetings.nu
382
+
383
+ use tools/utils.nu generate-prefix # visible only locally (we assume the file exists)
384
+
385
+ export def hello [name: string] {
386
+ greetings-helper "hello" "world"
387
+ }
388
+
389
+ export def hi [where: string] {
390
+ greetings-helper "hi" "there"
391
+ }
392
+
393
+ def greetings-helper [greeting: string, subject: string] {
394
+ $"(generate-prefix)($greeting) ($subject)!"
395
+ }
396
+ ```
397
+
398
+ then
399
+
400
+ ```nu
401
+ > use greetings.nu *
402
+
403
+
404
+ > hello "world"
405
+ hello world!
406
+
407
+ > hi "there"
408
+ hi there!
409
+
410
+ > greetings-helper "foo" "bar" # fails because 'greetings-helper' is not exported
411
+
412
+ > generate-prefix # fails because the command is imported only locally inside the module
413
+ ```
414
+
415
+ ### Dumping files into directory
416
+
417
+ A common pattern in traditional shells is dumping and auto-sourcing files from a directory (for example, loading custom completions). In Nushell, doing this directly is currently not possible, but directory modules can still be used.
418
+
419
+ Here we'll create a simple completion module with a submodule dedicated to some Git completions:
420
+
421
+ 1. Create the completion directory
422
+ `mkdir ($nu.default-config-dir | path join completions)`
423
+ 2. Create an empty `mod.nu` for it
424
+ `touch ($nu.default-config-dir | path join completions mod.nu)`
425
+ 3. Put the following snippet in `git.nu` under the `completions` directory
426
+ ```nu
427
+ export extern main [
428
+ --version(-v)
429
+ -C: string
430
+ # ... etc.
431
+ ]
432
+
433
+ export extern add [
434
+ --verbose(-v)
435
+ --dry-run(-n)
436
+ # ... etc.
437
+ ]
438
+
439
+ export extern checkout [
440
+ branch: string@complete-git-branch
441
+ ]
442
+
443
+ def complete-git-branch [] {
444
+ # ... code to list git branches
445
+ }
446
+ ```
447
+ 4. Add `export module git.nu` to `mod.nu`
448
+ 5. Add the parent of the `completions` directory to your NU_LIB_DIRS inside `env.nu`
449
+ ```nu
450
+ $env.NU_LIB_DIRS = [
451
+ ...
452
+ $nu.default-config-dir
453
+ ]
454
+ ```
455
+ 6. import the completions to Nushell in your `config.nu`
456
+ `use completions *`
457
+ Now you've set up a directory where you can put your completion files and you should have some Git completions the next time you start Nushell
458
+
459
+ > **Note**
460
+ > This will use the file name (in our example `git` from `git.nu`) as the module name. This means some completions might not work if the definition has the base command in it's name.
461
+ > For example, if you defined our known externals in our `git.nu` as `export extern 'git push' []`, etc. and followed the rest of the steps, you would get subcommands like `git git push`, etc.
462
+ > You would need to call `use completions git *` to get the desired subcommands. For this reason, using `main` as outlined in the step above is the preferred way to define subcommands.
463
+
464
+ ### Setting environment + aliases (conda style)
465
+
466
+ `def --env` commands, `export-env` block and aliases can be used to dynamically manipulate "virtual environments" (a concept well known from Python).
467
+
468
+ We use it in our official virtualenv integration https://github.com/pypa/virtualenv/blob/main/src/virtualenv/activation/nushell/activate.nu
469
+
470
+ Another example could be our unofficial Conda module: https://github.com/nushell/nu_scripts/blob/f86a060c10f132407694e9ba0f536bfe3ee51efc/modules/virtual_environments/conda.nu
471
+
472
+ > **Warning**
473
+ > Work In Progress
474
+
475
+ ## Hiding
476
+
477
+ Any custom command or alias, imported from a module or not, can be "hidden", restoring the previous definition.
478
+ We do this with the [`hide`](/commands/docs/hide.md) command:
479
+
480
+ ```nu
481
+ > def foo [] { "foo" }
482
+
483
+ > foo
484
+ foo
485
+
486
+ > hide foo
487
+
488
+ > foo # error! command not found!
489
+ ```
490
+
491
+ The [`hide`](/commands/docs/hide.md) command also accepts import patterns, just like [`use`](/commands/docs/use.md).
492
+ The import pattern is interpreted slightly differently, though.
493
+ It can be one of the following:
494
+
495
+ `hide foo` or `hide greetings`
496
+
497
+ - If the name is a custom command or an environment variable, hides it directly. Otherwise:
498
+ - If the name is a module name, hides all of its exports prefixed with the module name
499
+
500
+ `hide greetings hello`
501
+
502
+ - Hides only the prefixed command / environment variable
503
+
504
+ `hide greetings [hello, hi]`
505
+
506
+ - Hides only the prefixed commands / environment variables
507
+
508
+ `hide greetings *`
509
+
510
+ - Hides all of the module's exports, without the prefix
511
+
512
+ > **Note**
513
+ > `hide` is not a supported keyword at the root of a module (unlike `def` etc.)
moving_around.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Moving around your system
2
+
3
+ Early shells allow you to move around your filesystem and run commands, and modern shells like Nu allow you to do the same. Let's take a look at some of the common commands you might use when interacting with your system.
4
+
5
+ ## Viewing directory contents
6
+
7
+ @[code](@snippets/moving_around/ls_example.sh)
8
+
9
+ As we've seen in other chapters, [`ls`](/commands/docs/ls.md) is a command for viewing the contents of a path. Nu will return the contents as a table that we can use.
10
+
11
+ The [`ls`](/commands/docs/ls.md) command also takes an optional argument, to change what you'd like to view. For example, we can list the files that end in ".md"
12
+
13
+ @[code](@snippets/moving_around/ls_shallow_glob_example.sh)
14
+
15
+ ## Glob patterns (wildcards)
16
+
17
+ The asterisk (\*) in the above optional argument "\*.md" is sometimes called a wildcard or a glob. It lets us match anything. You could read the glob "\*.md" as "match any filename, so long as it ends with '.md' "
18
+
19
+ The most general glob is `*`, which will match all paths. More often, you'll see this pattern used as part of another pattern, for example `*.bak` and `temp*`.
20
+
21
+ In Nushell, we also support double `*` to talk about traversing deeper paths that are nested inside of other directories. For example, `ls **/*` will list all the non-hidden paths nested under the current directory.
22
+
23
+ @[code](@snippets/moving_around/ls_deep_glob_example.sh)
24
+
25
+ Here, we're looking for any file that ends with ".md", and the two asterisks further say "in any directory starting from here".
26
+
27
+ In other shells (like bash), glob expansion happens in the shell and the invoked program (`ls` in the example above) receives a list of matched files. In Nushell however, the string you enter is passed "as is" to the command, and some commands (like `ls`, `mv`, `cp` and `rm`) interpret their input string as a glob pattern. For example the [`ls` command's help page](https://www.nushell.sh/commands/docs/ls.html) shows that it takes the parameter: `pattern: the glob pattern to use (optional)`.
28
+
29
+ Globbing syntax in these commands not only supports `*`, but also matching [single characters with `?` and character groups with `[...]`](https://docs.rs/nu-glob/latest/nu_glob/struct.Pattern.html). Note that this is a more limited syntax than what the dedicated [`glob` Nushell command](https://www.nushell.sh/commands/docs/glob.html) supports.
30
+
31
+ Escaping `*`, `?`, `[]` works by quoting them with single quotes or double quotes. To show the contents of a directory named `[slug]`, use `ls "[slug]"` or `ls '[slug]'`.
32
+ Note that backtick quote doesn't escape glob, for example: <code>cp `test dir/*`</code> will copy all files inside `test dir` to current direcroty.
33
+
34
+ ## Changing the current directory
35
+
36
+ @[code](@snippets/moving_around/cd_example.sh)
37
+
38
+ To change from the current directory to a new one, we use the [`cd`](/commands/docs/cd.md) command. Just as in other shells, we can use either the name of the directory, or if we want to go up a directory we can use the `..` shortcut.
39
+
40
+ Changing the current working directory can also be done if [`cd`](/commands/docs/cd.md) is omitted and a path by itself is given:
41
+
42
+ @[code](@snippets/moving_around/cd_without_command_example.sh)
43
+
44
+ **Note:** changing the directory with [`cd`](/commands/docs/cd.md) changes the `PWD` environment variable. This means that a change of a directory is kept to the current block. Once you exit the block, you'll return to the previous directory. You can learn more about working with this in the [environment chapter](./environment.md).
45
+
46
+ ## Filesystem commands
47
+
48
+ Nu also provides some basic filesystem commands that work cross-platform.
49
+
50
+ We can move an item from one place to another using the [`mv`](/commands/docs/mv.md) command:
51
+
52
+ @[code](@snippets/moving_around/mv_example.sh)
53
+
54
+ We can copy an item from one location to another with the [`cp`](/commands/docs/cp.md) command:
55
+
56
+ @[code](@snippets/moving_around/cp_example.sh)
57
+
58
+ We can remove an item with the [`rm`](/commands/docs/rm.md) command:
59
+
60
+ @[code](@snippets/moving_around/rm_example.sh)
61
+
62
+ The three commands also can use the glob capabilities we saw earlier with [`ls`](/commands/docs/ls.md).
63
+
64
+ Finally, we can create a new directory using the [`mkdir`](/commands/docs/mkdir.md) command:
65
+
66
+ @[code](@snippets/moving_around/mkdir_example.sh)
nu_as_a_shell.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Nu as a Shell
2
+
3
+ The [Nu Fundamentals](nu_fundamentals.md) and [Programming in Nu](programming_in_nu.md) chapter focused mostly on the language aspects of Nushell.
4
+ This chapter sheds the light on the parts of Nushell that are related to the Nushell interpreter (the Nushell [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)).
5
+ Some of the concepts are directly a part of the Nushell programming language (such as environment variables) while others are implemented purely to enhance the interactive experience (such as hooks) and thus are not present when, for example, running a script.
6
+
7
+ Many parameters of Nushell can be [configured](configuration.md).
8
+ The config itself is stored as an environment variable.
9
+ Furthermore, Nushell has several different configuration files that are run on startup where you can put custom commands, aliases, etc.
10
+
11
+ A big feature of any shell are [environment variables](environment.md).
12
+ In Nushell, environment variables are scoped and can have any type supported by Nushell.
13
+ This brings in some additional design considerations so please refer to the linked section for more details.
14
+
15
+ The other sections explain how to work with [stdout, stderr and exit codes](stdout_stderr_exit_codes.md), how to [escape a command call to the external command call](escaping.md), and how to [configure 3rd party prompts](3rdpartyprompts.md) to work with Nushell.
16
+
17
+ An interesting feature of Nushell is [shells](shells_in_shells.md) which let you work in multiple directories simultaneously.
18
+
19
+ Nushell also has its own line editor [Reedline](line_editor.md).
20
+ With Nushell's config, it is possible to configure some of the Reedline's features, such as the prompt, keybindings, history, or menus.
21
+
22
+ It is also possible to define [custom signatures for external commands](externs.md) which lets you define [custom completions](custom_completions.md) for them (the custom completions work also for Nushell custom commands).
23
+
24
+ [Coloring and Theming in Nu](coloring_and_theming.md) goes into more detail about how to configure Nushell's appearance.
25
+
26
+ If you want to schedule some commands to run in the background, [Background task in Nu](background_task.md) provide a simple guideline for you to follow.
27
+
28
+ And finally, [hooks](hooks.md) allow you to insert fragments of Nushell code to run at certain events.
nu_fundamentals.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Nu Fundamentals
2
+
3
+ This chapter explains some of the fundamentals of the Nushell programming language.
4
+ After going through it, you should have an idea how to write simple Nushell programs.
5
+
6
+ Nushell has a rich type system.
7
+ You will find typical data types such as strings or integers and less typical data types, such as cell paths.
8
+ Furthermore, one of the defining features of Nushell is the notion of _structured data_ which means that you can organize types into collections: lists, records, or tables.
9
+ Contrary to the traditional Unix approach where commands communicate via plain text, Nushell commands communicate via these data types.
10
+ All of the above is explained in [Types of Data](types_of_data.md).
11
+
12
+ [Loading Data](loading_data.md) explains how to read common data formats, such as JSON, into _structured data_. This includes our own "NUON" data format.
13
+
14
+ Just like Unix shells, Nushell commands can be composed into [pipelines](pipelines.md) to pass and modify a stream of data.
15
+
16
+ Some data types have interesting features that deserve their own sections: [strings](working_with_strings.md), [lists](working_with_lists.md), and [tables](working_with_tables.md).
17
+ Apart from explaining the features, these sections also show how to do some common operations, such as composing strings or updating values in a list.
18
+
19
+ Finally, [Command Reference](/commands/) lists all the built-in commands with brief descriptions.
20
+ Note that you can also access this info from within Nushell using the [`help`](/commands/docs/help.md) command.
nushell_map.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Nu map from other shells and domain specific languages
2
+
3
+ The idea behind this table is to help you understand how Nu builtins and plugins relate to other known shells and domain specific languages. We've tried to produce a map of relevant Nu commands and what their equivalents are in other languages. Contributions are welcome.
4
+
5
+ Note: this table assumes Nu 0.43 or later.
6
+
7
+
8
+ | Nushell | SQL | .Net LINQ (C#) | PowerShell (without external modules) | Bash |
9
+ | ---------------------- | ----------------------------- | ---------------------------------------------------- | ------------------------------------------ | ----------------------------------------------- |
10
+ | alias | | | alias | alias |
11
+ | append | | Append | -Append | |
12
+ | math avg | avg | Average | Measure-Object, measure | |
13
+ | calc, `<math expression>` | math operators | Aggregate, Average, Count, Max, Min, Sum | | bc |
14
+ | cd | | | Set-Location, cd | cd |
15
+ | clear | | | Clear-Host | clear |
16
+ | config | | | $Profile | vi .bashrc, .profile |
17
+ | cp | | | Copy-Item, cp, copy | cp |
18
+ | date | NOW() / getdate() | DateTime class | Get-Date | date |
19
+ | du | | | | du |
20
+ | each | cursor | | ForEach-Object, foreach, for | |
21
+ | exit | | | exit | exit |
22
+ | http | | HttpClient,WebClient, HttpWebRequest/Response | Invoke-WebRequest | wget |
23
+ | first | top, limit | First, FirstOrDefault | Select-Object -First | head |
24
+ | format | | String.Format | String.Format | |
25
+ | from | import flatfile, openjson, cast(variable as xml) | | Import/ConvertFrom-{Csv,Xml,Html,Json} | |
26
+ | get | | Select | (cmd).column | |
27
+ | group-by | group by | GroupBy, group | Group-Object, group | |
28
+ | help | sp_help | | Get-Help, help, man | man |
29
+ | history | | | Get-History, history | history |
30
+ | is-empty | is null | String.InNullOrEmpty | String.InNullOrEmpty | |
31
+ | kill | | | Stop-Process, kill | kill |
32
+ | last | | Last, LastOrDefault | Select-Object -Last | tail |
33
+ | length | count | Count | Measure-Object, measure | wc |
34
+ | lines | | | File.ReadAllLines | |
35
+ | ls | | | Get-ChildItem, dir, ls | ls |
36
+ | mkdir | | | mkdir, md | mkdir |
37
+ | mv | | | Move-Item, mv, move, mi | mv |
38
+ | nth | limit x offset y, rownumber = | ElementAt | [x], indexing operator, ElementAt | |
39
+ | open | | | Get-Content, gc, cat, type | cat |
40
+ | print | print, union all | | Write-Output, write | echo |
41
+ | transpose | pivot | | | |
42
+ | ps | | | Get-Process, ps, gps | ps |
43
+ | pwd | | | Get-Location, pwd | pwd |
44
+ | range | | Range | 1..10, 'a'..'f' | |
45
+ | reduce | | Aggregate | | |
46
+ | rename | | | Rename-Item, ren, rni | mv |
47
+ | reverse | | Reverse | [Array]::Reverse($var) | |
48
+ | rm | | | Remove-Item, del, erase, rd, ri, rm, rmdir | rm |
49
+ | save | | | Write-Output, Out-File | > foo.txt |
50
+ | select | select | Select | Select-Object, select | |
51
+ | shuffle | | Random | Sort-Object {Get-Random} | |
52
+ | size | | | Measure-Object, measure | wc |
53
+ | skip | where row_number() | Skip | Select-Object -Skip | |
54
+ | skip until | | SkipWhile | | |
55
+ | skip while | | SkipWhile | | |
56
+ | sort-by | order by | OrderBy, OrderByDescending, ThenBy, ThenByDescending | Sort-Object, sort | |
57
+ | split-by | | Split | Split | |
58
+ | str | string functions | String class | String class | |
59
+ | str join | concat_ws | Join | Join-String | |
60
+ | str trim | rtrim, ltrim | Trim, TrimStart, TrimEnd | Trim | |
61
+ | sum | sum | Sum | Measure-Object, measure | |
62
+ | sys | | | Get-ComputerInfo | uname, lshw, lsblk, lscpu, lsusb, hdparam, free |
63
+ | table | | | Format-Table, ft, Format-List, fl | |
64
+ | take | top, limit | Take | Select-Object -First | head |
65
+ | take until | | TakeWhile | | |
66
+ | take while | | TakeWhile | | |
67
+ | timeit | | | Measure-Command | time |
68
+ | to | | | Export/ConvertTo-{Csv,Xml,Html,Json} | |
69
+ | touch | | | Set-Content | touch |
70
+ | uniq | distinct | Distinct | Get-Unique, gu | uniq |
71
+ | upsert | As | | | |
72
+ | version | select @@version | | $PSVersionTable | |
73
+ | with-env | | | $env:FOO = 'bar' | export foo = "bar" |
74
+ | where | where | Where | Where-Object, where, "?" operator | |
75
+ | which | | | | which |
nushell_map_functional.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Nu map from functional languages
2
+
3
+ The idea behind this table is to help you understand how Nu builtins and plugins relate to functional languages. We've tried to produce a map of relevant Nu commands and what their equivalents are in other languages. Contributions are welcome.
4
+
5
+ Note: this table assumes Nu 0.43 or later.
6
+
7
+ | Nushell | Clojure | Tablecloth (Ocaml / Elm) | Haskell |
8
+ | ------------ | ---------------------------- | ------------------------------- | ------------------------ |
9
+ | append | conj, into, concat | append, (++), concat, concatMap | (++) |
10
+ | into binary | Integer/toHexString | | showHex |
11
+ | count | count | length, size | length, size |
12
+ | date | java.time.LocalDate/now | | |
13
+ | each | map, mapv, iterate | map, forEach | map, mapM |
14
+ | exit | System/exit | | |
15
+ | first | first | head | head |
16
+ | format | format | | Text.Printf.printf |
17
+ | group-by | group-by | | group, groupBy |
18
+ | help | doc | | |
19
+ | is-empty | empty? | isEmpty | |
20
+ | last | last, peek, take-last | last | last |
21
+ | lines | | | lines, words, split-with |
22
+ | match | | match (Ocaml), case (Elm) | case |
23
+ | nth | nth | Array.get | lookup |
24
+ | open | with-open | | |
25
+ | transpose | (apply mapv vector matrix) | | transpose |
26
+ | prepend | cons | cons, :: | :: |
27
+ | print | println | | putStrLn, print |
28
+ | range, 1..10 | range | range | 1..10, 'a'..'f' |
29
+ | reduce | reduce, reduce-kv | foldr | foldr |
30
+ | reverse | reverse, rseq | reverse, reverseInPlace | reverse |
31
+ | select | select-keys | | |
32
+ | shuffle | shuffle | | |
33
+ | size | count | | size, length |
34
+ | skip | rest | tail | tail |
35
+ | skip until | drop-while | | |
36
+ | skip while | drop-while | dropWhile | dropWhile, dropWhileEnd |
37
+ | sort-by | sort, sort-by, sorted-set-by | sort, sortBy, sortWith | sort, sortBy |
38
+ | split row | split, split-{at,with,lines} | split, words, lines | split, words, lines |
39
+ | str | clojure.string functions | String functions | |
40
+ | str join | join | concat | intercalate |
41
+ | str trim | trim, triml, trimr | trim, trimLeft, trimRight | strip |
42
+ | sum | apply + | sum | sum |
43
+ | take | take, drop-last, pop | take, init | take, init |
44
+ | take until | take-while | takeWhile | takeWhile |
45
+ | take while | take-while | takeWhile | takeWhile |
46
+ | uniq | set | Set.empty | Data.Set |
47
+ | where | filter, filterv, select | filter, filterMap | filter |
nushell_map_imperative.md ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Nu map from imperative languages
2
+
3
+ The idea behind this table is to help you understand how Nu built-ins and plugins relate to imperative languages. We've tried to produce a map of programming-relevant Nu commands and what their equivalents are in other languages. Contributions are welcome.
4
+
5
+ Note: this table assumes Nu 0.43 or later.
6
+
7
+ | Nushell | Python | Kotlin (Java) | C++ | Rust |
8
+ | ------------ | ------------------------------------ | --------------------------------------------------- | ----------------------- | -------------------------------------------------- |
9
+ | append | list.append, set.add | add | push_back, emplace_back | push, push_back |
10
+ | math avg | statistics.mean | | | |
11
+ | calc, = math | math operators | math operators | math operators | math operators |
12
+ | count | len | size, length | length | len |
13
+ | cp | shutil.copy | | | fs::copy |
14
+ | date | datetime.date.today | java.time.LocalDate.now | | |
15
+ | drop | list[:-3] | | | |
16
+ | du | shutil.disk_usage | | | |
17
+ | each | for | for | for | for |
18
+ | exit | exit | System.exit, kotlin.system.exitProcess | exit | exit |
19
+ | http get | urllib.request.urlopen | | | |
20
+ | first | list[:x] | List[0], peek | vector[0], top | Vec[0] |
21
+ | format | format | format | format | format! |
22
+ | from | csv, json, sqlite3 | | | |
23
+ | get | dict[\"key\"] | Map[\"key\"] | map[\"key\"] | HashMap["key"], get, entry |
24
+ | group-by | itertools.groupby | groupBy | | group_by |
25
+ | headers | keys | | | |
26
+ | help | help | | | |
27
+ | insert | dict[\"key\"] = val | | map.insert({ 20, 130 }) | map.insert(\"key\", val) |
28
+ | is-empty | is None, is [] | isEmpty | empty | is_empty |
29
+ | take | list[:x] | | | &Vec[..x] |
30
+ | take until | itertools.takewhile | | | |
31
+ | take while | itertools.takewhile | | | |
32
+ | kill | os.kill | | | |
33
+ | last | list[-x:] | | | &Vec[Vec.len()-1] |
34
+ | lines | split, splitlines | split | views::split | split, split_whitespace, rsplit, lines |
35
+ | ls | os.listdir | | | fs::read_dir |
36
+ | match | match | when | | match |
37
+ | merge | dict.append | | | map.extend |
38
+ | mkdir | os.mkdir | | | fs::create_dir |
39
+ | mv | shutil.move | | | fs::rename |
40
+ | get | list[x] | List[x] | vector[x] | Vec[x] |
41
+ | open | open | | | |
42
+ | transpose | zip(\*matrix) | | | |
43
+ | http post | urllib.request.urlopen | | | |
44
+ | prepend | deque.appendleft | | | |
45
+ | print | print | println | printf | println! |
46
+ | ps | os.listdir('/proc') | | | |
47
+ | pwd | os.getcwd | | | env::current_dir |
48
+ | range | range | .., until, downTo, step | iota | .. |
49
+ | reduce | functools.reduce | reduce | reduce | fold, rfold, scan |
50
+ | reject | del | | | |
51
+ | rename | dict[\"key2\"] = dict.pop(\"key\") | | | map.insert(\"key2\", map.remove(\"key\").unwrap()); |
52
+ | reverse | reversed, list.reverse | reverse, reversed, asReversed | reverse | rev |
53
+ | rm | os.remove | | | |
54
+ | save | io.TextIOWrapper.write | | | |
55
+ | select | {k:dict[k] for k in keys} | | | |
56
+ | shuffle | random.shuffle | | | |
57
+ | size | len | | | len |
58
+ | skip | list[x:] | | | &Vec[x..],skip |
59
+ | skip until | itertools.dropwhile | | | |
60
+ | skip while | itertools.dropwhile | | | skip_while |
61
+ | sort-by | sorted, list.sort | sortedBy, sortedWith, Arrays.sort, Collections.sort | sort | sort |
62
+ | split row | str.split{,lines}, re.split | split | views::split | split |
63
+ | str | str functions | String functions | string functions | &str, String functions |
64
+ | str join | str.join | joinToString | | join |
65
+ | str trim | strip, rstrip, lstrip | trim, trimStart, trimEnd | regex | trim, trim*{start,end}, strip*{suffix,prefix} |
66
+ | sum | sum | sum | reduce | sum |
67
+ | sys | sys | | | |
68
+ | to | import csv, json, sqlite3 | | | |
69
+ | touch | open(path, 'a').close() | | | |
70
+ | uniq | set | Set | set | HashSet |
71
+ | upsert | dict[\"key\"] = val | | | |
72
+ | version | sys.version, sys.version_info | | | |
73
+ | with-env | os.environ | | | |
74
+ | where | filter | filter | filter | filter |
75
+ | which | shutil.which | | | |
76
+ | wrap | { "key" : val } | | | |
nushell_operator_map.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Nushell operator map
2
+
3
+ The idea behind this table is to help you understand how Nu operators relate to other language operators. We've tried to produce a map of all the nushell operators and what their equivalents are in other languages. Contributions are welcome.
4
+
5
+ Note: this table assumes Nu 0.14.1 or later.
6
+
7
+ | Nushell | SQL | Python | .NET LINQ (C#) | PowerShell | Bash |
8
+ | ------- | -------- | ------------------ | -------------------- | ---------------------- | ------------------ |
9
+ | == | = | == | == | -eq, -is | -eq |
10
+ | != | !=, <> | != | != | -ne, -isnot | -ne |
11
+ | < | < | < | < | -lt | -lt |
12
+ | <= | <= | <= | <= | -le | -le |
13
+ | > | > | > | > | -gt | -gt |
14
+ | >= | >= | >= | >= | -ge | -ge |
15
+ | =~ | like | re, in, startswith | Contains, StartsWith | -like, -contains | =~ |
16
+ | !~ | not like | not in | Except | -notlike, -notcontains | ! "str1" =~ "str2" |
17
+ | + | + | + | + | + | + |
18
+ | - | - | - | - | - | - |
19
+ | \* | \* | \* | \* | \* | \* |
20
+ | / | / | / | / | / | / |
21
+ | \*\* | pow | \*\* | Power | Pow | \*\* |
22
+ | in | in | re, in, startswith | Contains, StartsWith | -In | case in |
23
+ | not-in | not in | not in | Except | -NotIn | |
24
+ | and | and | and | && | -And, && | -a, && |
25
+ | or | or | or | \|\| | -Or, \|\| | -o, \|\| |
operators.md ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Operators
2
+
3
+ Nushell supports the following operators for common math, logic, and string operations:
4
+
5
+ | Operator | Description |
6
+ | ------------- | ------------------------------------------------------- |
7
+ | `+` | add |
8
+ | `-` | subtract |
9
+ | `*` | multiply |
10
+ | `/` | divide |
11
+ | `//` | floor division |
12
+ | `mod` | modulo |
13
+ | `**` | exponentiation (power) |
14
+ | `==` | equal |
15
+ | `!=` | not equal |
16
+ | `<` | less than |
17
+ | `<=` | less than or equal |
18
+ | `>` | greater than |
19
+ | `>=` | greater than or equal |
20
+ | `=~` | regex match / string contains another |
21
+ | `!~` | inverse regex match / string does *not* contain another |
22
+ | `in` | value in list |
23
+ | `not-in` | value not in list |
24
+ | `not` | logical not |
25
+ | `and` | and two Boolean expressions (short-circuits) |
26
+ | `or` | or two Boolean expressions (short-circuits) |
27
+ | `xor` | exclusive or two boolean expressions |
28
+ | `bit-or` | bitwise or |
29
+ | `bit-xor` | bitwise xor |
30
+ | `bit-and` | bitwise and |
31
+ | `bit-shl` | bitwise shift left |
32
+ | `bit-shr` | bitwise shift right |
33
+ | `starts-with` | string starts with |
34
+ | `ends-with` | string ends with |
35
+ | `++` | append lists |
36
+
37
+
38
+ Parentheses can be used for grouping to specify evaluation order or for calling commands and using the results in an expression.
39
+
40
+ ## Order of Operations
41
+
42
+ Operations are evaluated in the following order (from highest precedence to lowest):
43
+
44
+ - Parentheses (`()`)
45
+ - Exponentiation/Power (`**`)
46
+ - Multiply (`*`), Divide (`/`), Integer/Floor Division (`//`), and Modulo (`mod`)
47
+ - Add (`+`) and Subtract (`-`)
48
+ - Bit shifting (`bit-shl`, `bit-shr`)
49
+ - Comparison operations (`==`, `!=`, `<`, `>`, `<=`, `>=`), membership tests (`in`, `not-in`, `starts-with`, `ends-with`), regex matching (`=~`, `!~`), and list appending (`++`)
50
+ - Bitwise and (`bit-and`)
51
+ - Bitwise xor (`bit-xor`)
52
+ - Bitwise or (`bit-or`)
53
+ - Logical and (`&&`, `and`)
54
+ - Logical xor (`xor`)
55
+ - Logical or (`||`, `or`)
56
+ - Assignment operations
57
+
58
+ ```
59
+ > 3 * (1 + 2)
60
+ 9
61
+ ```
62
+
63
+ ## Types
64
+
65
+ Not all operations make sense for all data types.
66
+ If you attempt to perform an operation on non-compatible data types, you will be met with an error message that should explain what went wrong:
67
+ ```nu
68
+ > "spam" - 1
69
+ Error: nu::parser::unsupported_operation (link)
70
+
71
+ × Types mismatched for operation.
72
+ ╭─[entry #49:1:1]
73
+ 1 │ "spam" - 1
74
+ · ───┬── ┬ ┬
75
+ · │ │ ╰── int
76
+ · │ ╰── doesn't support these values.
77
+ · ╰── string
78
+ ╰────
79
+ help: Change string or int to be the right types and try again.
80
+ ```
81
+
82
+ The rules might sometimes feel a bit strict, but on the other hand there should be less unexpected side effects.
83
+
84
+ ## Regular Expression / string-contains Operators
85
+
86
+ The `=~` and `!~` operators provide a convenient way to evaluate [regular expressions](https://cheatography.com/davechild/cheat-sheets/regular-expressions/). You don't need to know regular expressions to use them - they're also an easy way to check whether 1 string contains another.
87
+
88
+ - `string =~ pattern` returns **true** if `string` contains a match for `pattern`, and **false** otherwise.
89
+ - `string !~ pattern` returns **false** if `string` contains a match for `pattern`, and **true** otherwise.
90
+
91
+ For example:
92
+
93
+ ```nu
94
+ foobarbaz =~ bar # returns true
95
+ foobarbaz !~ bar # returns false
96
+ ls | where name =~ ^nu # returns all files whose names start with "nu"
97
+ ```
98
+
99
+ Both operators use [the Rust regex crate's `is_match()` function](https://docs.rs/regex/latest/regex/struct.Regex.html#method.is_match).
100
+
101
+ ## Case Sensitivity
102
+
103
+ Operators are usually case-sensitive when operating on strings. There are a few ways to do case-insensitive work instead:
104
+
105
+ 1. In the regular expression operators, specify the `(?i)` case-insensitive mode modifier:
106
+
107
+ ```nu
108
+ "FOO" =~ "foo" # returns false
109
+ "FOO" =~ "(?i)foo" # returns true
110
+ ```
111
+
112
+ 2. Use the [`str contains`](/commands/docs/str_contains.md) command's `--insensitive` flag:
113
+
114
+ ```nu
115
+ "FOO" | str contains --insensitive "foo"
116
+ ```
117
+
118
+ 3. Convert strings to lowercase with [`str downcase`](/commands/docs/str_downcase.md) before comparing:
119
+
120
+ ```nu
121
+ ("FOO" | str downcase) == ("Foo" | str downcase)
122
+ ```
123
+
124
+ ## Spread operator
125
+
126
+ Nushell has a spread operator (`...`) for unpacking lists and records. You may be familiar with it
127
+ if you've used JavaScript before. Some languages use `*` for their spread/splat operator. It can
128
+ expand lists or records in places where multiple values or key-value pairs are expected.
129
+
130
+ There are three places you can use the spread operator:
131
+
132
+ - [In list literals](#in-list-literals)
133
+ - [In record literals](#in-record-literals)
134
+ - [In command calls](#in-command-calls)
135
+
136
+ ### In list literals
137
+
138
+ Suppose you have multiple lists you want to concatenate together, but you also want to intersperse
139
+ some individual values. This can be done with `append` and `prepend`, but the spread
140
+ operator can let you do it more easily.
141
+
142
+ ```nushell
143
+ > let dogs = [Spot, Teddy, Tommy]
144
+ > let cats = ["Mr. Humphrey Montgomery", Kitten]
145
+ > [
146
+ ...$dogs
147
+ Polly
148
+ ...($cats | each { |it| $"($it) \(cat\)" })
149
+ ...[Porky Bessie]
150
+ ...Nemo
151
+ ]
152
+ ╭───┬───────────────────────────────╮
153
+ │ 0 │ Spot │
154
+ │ 1 │ Teddy │
155
+ │ 2 │ Tommy │
156
+ │ 3 │ Polly │
157
+ │ 4 │ Mr. Humphrey Montgomery (cat) │
158
+ │ 5 │ Kitten (cat) │
159
+ │ 6 │ Porky │
160
+ │ 7 │ Bessie │
161
+ │ 8 │ ...Nemo │
162
+ ╰───┴───────────────────────────────╯
163
+ ```
164
+
165
+ The below code is an equivalent version using `append`:
166
+ ```nushell
167
+ > $dogs |
168
+ append Polly |
169
+ append ($cats | each { |it| $"($it) \(cat\)" }) |
170
+ append [Porky Bessie] |
171
+ append ...Nemo
172
+ ```
173
+
174
+ Note that each call to `append` results in the creation of a new list, meaning that in this second
175
+ example, 3 unnecessary intermediate lists are created. This is not the case with the spread operator,
176
+ so there may be (very minor) performance benefits to using `...` if you're joining lots of large
177
+ lists together, over and over.
178
+
179
+ You may have noticed that the last item of the resulting list above is `"...Nemo"`. This is because
180
+ inside list literals, it can only be used to spread lists, not strings. As such, inside list literals, it can
181
+ only be used before variables (`...$foo`), subexpressions (`...(foo)`), and list literals (`...[foo]`).
182
+
183
+ The `...` also won't be recognized as the spread operator if there's any whitespace between it and
184
+ the next expression:
185
+
186
+ ```nushell
187
+ > [ ... [] ]
188
+ ╭───┬────────────────╮
189
+ │ 0 │ ... │
190
+ │ 1 │ [list 0 items] │
191
+ ╰───┴────────────────╯
192
+ ```
193
+
194
+ This is mainly so that `...` won't be confused for the spread operator in commands such as `mv ... $dir`.
195
+
196
+ ### In record literals
197
+
198
+ Let's say you have a record with some configuration information and you want to add more fields to
199
+ this record:
200
+
201
+ ```nushell
202
+ > let config = { path: /tmp, limit: 5 }
203
+ ```
204
+
205
+ You can make a new record with all the fields of `$config` and some new additions using the spread
206
+ operator. You can use the spread multiple records inside a single record literal.
207
+
208
+ ```nushell
209
+ > {
210
+ ...$config,
211
+ users: [alice bob],
212
+ ...{ url: example.com },
213
+ ...(sys | get mem)
214
+ }
215
+ ╭────────────┬───────────────╮
216
+ │ path │ /tmp │
217
+ │ limit │ 5 │
218
+ │ │ ╭───┬───────╮ │
219
+ │ users │ │ 0 │ alice │ │
220
+ │ │ │ 1 │ bob │ │
221
+ │ │ ╰───┴───────╯ │
222
+ │ url │ example.com │
223
+ │ total │ 8.3 GB │
224
+ │ free │ 2.6 GB │
225
+ │ used │ 5.7 GB │
226
+ │ available │ 2.6 GB │
227
+ │ swap total │ 2.1 GB │
228
+ │ swap free │ 18.0 MB │
229
+ │ swap used │ 2.1 GB │
230
+ ╰────────────┴───────────────╯
231
+ ```
232
+
233
+ Similarly to lists, inside record literals, the spread operator can only be used before variables (`...$foo`),
234
+ subexpressions (`...(foo)`), and record literals (`...{foo:bar}`). Here too, there needs to be no
235
+ whitespace between the `...` and the next expression for it to be recognized as the spread operator.
236
+
237
+ ### In command calls
238
+
239
+ You can also spread arguments to a command, provided that it either has a rest parameter or is an
240
+ external command.
241
+
242
+ Here is an example custom command that has a rest parameter:
243
+
244
+ ```nushell
245
+ > def foo [ --flag req opt? ...args ] { [$flag, $req, $opt, $args] | to nuon }
246
+ ```
247
+
248
+ It has one flag (`--flag`), one required positional parameter (`req`), one optional positional parameter
249
+ (`opt?`), and rest parameter (`args`).
250
+
251
+ If you have a list of arguments to pass to `args`, you can spread it the same way you'd spread a list
252
+ [inside a list literal](#in-list-literals). The same rules apply: the spread operator is only
253
+ recognized before variables, subexpressions, and list literals, and no whitespace is allowed in between.
254
+
255
+ ```nushell
256
+ > foo "bar" "baz" ...[1 2 3] # With ..., the numbers are treated as separate arguments
257
+ [false, bar, baz, [1, 2, 3]]
258
+ > foo "bar" "baz" [1 2 3] # Without ..., [1 2 3] is treated as a single argument
259
+ [false, bar, baz, [[1, 2, 3]]]
260
+ ```
261
+
262
+ A more useful way to use the spread operator is if you have another command with a rest parameter
263
+ and you want it to forward its arguments to `foo`:
264
+
265
+ ```nushell
266
+ > def bar [ ...args ] { foo --flag "bar" "baz" ...$args }
267
+ > bar 1 2 3
268
+ [true, bar, baz, [1, 2, 3]]
269
+ ```
270
+
271
+ You can spread multiple lists in a single call, and also intersperse individual arguments:
272
+
273
+ ```nushell
274
+ > foo "bar" "baz" 1 ...[2 3] 4 5 ...(6..9 | take 2) last
275
+ [false, bar, baz, [1, 2, 3, 4, 5, 6, 7, last]]
276
+ ```
277
+
278
+ Flags/named arguments can go after a spread argument, just like they can go after regular rest arguments:
279
+
280
+ ```nushell
281
+ > foo "bar" "baz" 1 ...[2 3] --flag 4
282
+ [true, bar, baz, [1, 2, 3, 4]]
283
+ ```
284
+
285
+ If a spread argument comes before an optional positional parameter, that optional parameter is treated
286
+ as being omitted:
287
+
288
+ ```nushell
289
+ > foo "bar" ...[1 2] "not opt" # The null means no argument was given for opt
290
+ [false, bar, null, [1, 2, "not opt"]]
291
+ ```
overlays.md ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Overlays
2
+
3
+ Overlays act as "layers" of definitions (custom commands, aliases, environment variables) that can be activated and deactivated on demand.
4
+ They resemble virtual environments found in some languages, such as Python.
5
+
6
+ _Note: To understand overlays, make sure to check [Modules](modules.md) first as overlays build on top of modules._
7
+
8
+ ## Basics
9
+
10
+ First, Nushell comes with one default overlay called `zero`.
11
+ You can inspect which overlays are active with the [`overlay list`](/commands/docs/overlay_list.md) command.
12
+ You should see the default overlay listed there.
13
+
14
+ To create a new overlay, you first need a module:
15
+
16
+ ```nu
17
+ > module spam {
18
+ export def foo [] {
19
+ "foo"
20
+ }
21
+
22
+ export alias bar = "bar"
23
+
24
+ export-env {
25
+ load-env { BAZ: "baz" }
26
+ }
27
+ }
28
+ ```
29
+
30
+ We'll use this module throughout the chapter, so whenever you see `overlay use spam`, assume `spam` is referring to this module.
31
+
32
+ ::: tip
33
+ The module can be created by any of the three methods described in [Modules](modules.md):
34
+
35
+ - "inline" modules (used in this example)
36
+ - file
37
+ - directory
38
+ :::
39
+
40
+ To create the overlay, call [`overlay use`](/commands/docs/overlay_use.md):
41
+
42
+ ```nu
43
+ > overlay use spam
44
+
45
+ > foo
46
+ foo
47
+
48
+ > bar
49
+ bar
50
+
51
+ > $env.BAZ
52
+ baz
53
+
54
+ > overlay list
55
+ ───┬──────
56
+ 0 │ zero
57
+ 1 │ spam
58
+ ───┴──────
59
+ ```
60
+
61
+ It brought the module's definitions into the current scope and evaluated the [`export-env`](/commands/docs/export-env.md) block the same way as [`use`](/commands/docs/use.md) command would (see [Modules](modules.md#environment-variables) chapter).
62
+
63
+ ::: tip
64
+ In the following sections, the `>` prompt will be preceded by the name of the last active overlay.
65
+ `(spam)> some-command` means the `spam` overlay is the last active overlay when the command was typed.
66
+ :::
67
+
68
+ ## Removing an Overlay
69
+
70
+ If you don't need the overlay definitions anymore, call [`overlay hide`](/commands/docs/overlay_remove.md):
71
+
72
+ ```nu
73
+ (spam)> overlay hide spam
74
+
75
+ (zero)> foo
76
+ Error: Can't run executable...
77
+
78
+ (zero)> overlay list
79
+ ───┬──────
80
+ 0 │ zero
81
+ ───┴──────
82
+ ```
83
+
84
+ The overlays are also scoped.
85
+ Any added overlays are removed at the end of the scope:
86
+
87
+ ```nu
88
+ (zero)> do { overlay use spam; foo } # overlay is active only inside the block
89
+ foo
90
+
91
+ (zero)> overlay list
92
+ ───┬──────
93
+ 0 │ zero
94
+ ───┴──────
95
+ ```
96
+
97
+ The last way to remove an overlay is to call [`overlay hide`](/commands/docs/overlay_remove.md) without an argument which will remove the last active overlay.
98
+
99
+ ## Overlays Are Recordable
100
+
101
+ Any new definition (command, alias, environment variable) is recorded into the last active overlay:
102
+
103
+ ```nu
104
+ (zero)> overlay use spam
105
+
106
+ (spam)> def eggs [] { "eggs" }
107
+ ```
108
+
109
+ Now, the `eggs` command belongs to the `spam` overlay.
110
+ If we remove the overlay, we can't call it anymore:
111
+
112
+ ```nu
113
+ (spam)> overlay hide spam
114
+
115
+ (zero)> eggs
116
+ Error: Can't run executable...
117
+ ```
118
+
119
+ But we can bring it back!
120
+
121
+ ```nu
122
+ (zero)> overlay use spam
123
+
124
+ (spam)> eggs
125
+ eggs
126
+ ```
127
+
128
+ Overlays remember what you add to them and store that information even if you remove them.
129
+ This can let you repeatedly swap between different contexts.
130
+
131
+ ::: tip
132
+ Sometimes, after adding an overlay, you might not want custom definitions to be added into it.
133
+ The solution can be to create a new empty overlay that would be used just for recording the custom changes:
134
+
135
+ ```nu
136
+ (zero)> overlay use spam
137
+
138
+ (spam)> module scratchpad { }
139
+
140
+ (spam)> overlay use scratchpad
141
+
142
+ (scratchpad)> def eggs [] { "eggs" }
143
+ ```
144
+
145
+ The `eggs` command is added into `scratchpad` while keeping `spam` intact.
146
+
147
+ To make it less verbose, you can use the [`overlay new`](/commands/docs/overlay_new.md) command:
148
+
149
+ ```nu
150
+ (zero)> overlay use spam
151
+
152
+ (spam)> overlay new scratchpad
153
+
154
+ (scratchpad)> def eggs [] { "eggs" }
155
+ ```
156
+
157
+ :::
158
+
159
+ ## Prefixed Overlays
160
+
161
+ The [`overlay use`](/commands/docs/overlay_use.md) command would take all commands and aliases from the module and put them directly into the current namespace.
162
+ However, you might want to keep them as subcommands behind the module's name.
163
+ That's what `--prefix` is for:
164
+
165
+ ```nu
166
+ (zero)> module spam {
167
+ export def foo [] { "foo" }
168
+ }
169
+
170
+ (zero)> overlay use --prefix spam
171
+
172
+ (spam)> spam foo
173
+ foo
174
+ ```
175
+
176
+ Note that this does not apply for environment variables.
177
+
178
+ ## Rename an Overlay
179
+
180
+ You can change the name of the added overlay with the `as` keyword:
181
+
182
+ ```nu
183
+ (zero)> module spam { export def foo [] { "foo" } }
184
+
185
+ (zero)> overlay use spam as eggs
186
+
187
+ (eggs)> foo
188
+ foo
189
+
190
+ (eggs)> overlay hide eggs
191
+
192
+ (zero)>
193
+ ```
194
+
195
+ This can be useful if you have a generic script name, such as virtualenv's `activate.nu` but you want a more descriptive name for your overlay.
196
+
197
+ ## Preserving Definitions
198
+
199
+ Sometimes, you might want to remove an overlay, but keep all the custom definitions you added without having to redefine them in the next active overlay:
200
+
201
+ ```nu
202
+ (zero)> overlay use spam
203
+
204
+ (spam)> def eggs [] { "eggs" }
205
+
206
+ (spam)> overlay hide --keep-custom spam
207
+
208
+ (zero)> eggs
209
+ eggs
210
+ ```
211
+
212
+ The `--keep-custom` flag does exactly that.
213
+
214
+ One can also keep a list of environment variables that were defined inside an overlay, but remove the rest, using the `--keep-env` flag:
215
+
216
+ ```nu
217
+ (zero)> module spam {
218
+ export def foo [] { "foo" }
219
+ export-env { $env.FOO = "foo" }
220
+ }
221
+
222
+ (zero)> overlay use spam
223
+
224
+ (spam)> overlay hide spam --keep-env [ FOO ]
225
+
226
+ (zero)> foo
227
+ Error: Can't run executable...
228
+
229
+ (zero)> $env.FOO
230
+ foo
231
+ ```
232
+
233
+ ## Ordering Overlays
234
+
235
+ The overlays are arranged as a stack.
236
+ If multiple overlays contain the same definition, say `foo`, the one from the last active one would take precedence.
237
+ To bring an overlay to the top of the stack, you can call [`overlay use`](/commands/docs/overlay_use.md) again:
238
+
239
+ ```nu
240
+ (zero)> def foo [] { "foo-in-zero" }
241
+
242
+ (zero)> overlay use spam
243
+
244
+ (spam)> foo
245
+ foo
246
+
247
+ (spam)> overlay use zero
248
+
249
+ (zero)> foo
250
+ foo-in-zero
251
+
252
+ (zero)> overlay list
253
+ ───┬──────
254
+ 0 │ spam
255
+ 1 │ zero
256
+ ───┴──────
257
+ ```
258
+
259
+ Now, the `zero` overlay takes precedence.
parallelism.md ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Parallelism
2
+
3
+ Nushell now has early support for running code in parallel. This allows you to process elements of a stream using more hardware resources of your computer.
4
+
5
+ You will notice these commands with their characteristic `par-` naming. Each corresponds to a non-parallel version, allowing you to easily write code in a serial style first, and then go back and easily convert serial scripts into parallel scripts with a few extra characters.
6
+
7
+ ## par-each
8
+
9
+ The most common parallel command is [`par-each`](/commands/docs/par-each.md), a companion to the [`each`](/commands/docs/each.md) command.
10
+
11
+ Like [`each`](/commands/docs/each.md), [`par-each`](/commands/docs/par-each.md) works on each element in the pipeline as it comes in, running a block on each. Unlike [`each`](/commands/docs/each.md), [`par-each`](/commands/docs/par-each.md) will do these operations in parallel.
12
+
13
+ Let's say you wanted to count the number of files in each sub-directory of the current directory. Using [`each`](/commands/docs/each.md), you could write this as:
14
+
15
+ ```nu
16
+ > ls | where type == dir | each { |it|
17
+ { name: $it.name, len: (ls $it.name | length) }
18
+ }
19
+ ```
20
+
21
+ We create a record for each entry, and fill it with the name of the directory and the count of entries in that sub-directory.
22
+
23
+ On your machine, the times may vary. For this machine, it took 21 milliseconds for the current directory.
24
+
25
+ Now, since this operation can be run in parallel, let's convert the above to parallel by changing [`each`](/commands/docs/each.md) to [`par-each`](/commands/docs/par-each.md):
26
+
27
+ ```nu
28
+ > ls | where type == dir | par-each { |it|
29
+ { name: $it.name, len: (ls $it.name | length) }
30
+ }
31
+ ```
32
+
33
+ On this machine, it now runs in 6ms. That's quite a difference!
34
+
35
+ As a side note: Because [environment variables are scoped](environment.md#scoping), you can use [`par-each`](/commands/docs/par-each.md) to work in multiple directories in parallel (notice the [`cd`](/commands/docs/cd.md) command):
36
+
37
+ ```nu
38
+ > ls | where type == dir | par-each { |it|
39
+ { name: $it.name, len: (cd $it.name; ls | length) }
40
+ }
41
+ ```
42
+
43
+ You'll notice, if you look at the results, that they come back in different orders each run (depending on the number of hardware threads on your system). As tasks finish, and we get the correct result, we may need to add additional steps if we want our results in a particular order. For example, for the above, we may want to sort the results by the "name" field. This allows both [`each`](/commands/docs/each.md) and [`par-each`](/commands/docs/par-each.md) versions of our script to give the same result.
pipelines.md ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pipelines
2
+
3
+ One of the core designs of Nu is the pipeline, a design idea that traces its roots back decades to some of the original philosophy behind Unix. Just as Nu extends from the single string data type of Unix, Nu also extends the idea of the pipeline to include more than just text.
4
+
5
+ ## Basics
6
+
7
+ A pipeline is composed of three parts: the input, the filter, and the output.
8
+
9
+ ```nu
10
+ > open "Cargo.toml" | inc package.version --minor | save "Cargo_new.toml"
11
+ ```
12
+
13
+ The first command, `open "Cargo.toml"`, is an input (sometimes also called a "source" or "producer"). This creates or loads data and feeds it into a pipeline. It's from input that pipelines have values to work with. Commands like [`ls`](/commands/docs/ls.md) are also inputs, as they take data from the filesystem and send it through the pipelines so that it can be used.
14
+
15
+ The second command, `inc package.version --minor`, is a filter. Filters take the data they are given and often do something with it. They may change it (as with the [`inc`](/commands/docs/inc.md) command in our example), or they may do another operation, like logging, as the values pass through.
16
+
17
+ The last command, `save "Cargo_new.toml"`, is an output (sometimes called a "sink"). An output takes input from the pipeline and does some final operation on it. In our example, we save what comes through the pipeline to a file as the final step. Other types of output commands may take the values and view them for the user.
18
+
19
+ The `$in` variable will collect the pipeline into a value for you, allowing you to access the whole stream as a parameter:
20
+
21
+ ```nu
22
+ > [1 2 3] | $in.1 * $in.2
23
+ 6
24
+ ```
25
+
26
+ ## Multi-line pipelines
27
+
28
+ If a pipeline is getting a bit long for one line, you can enclose it within `(` and `)` to create a subexpression:
29
+
30
+ ```nu
31
+ (
32
+ "01/22/2021" |
33
+ parse "{month}/{day}/{year}" |
34
+ get year
35
+ )
36
+ ```
37
+
38
+ Also see [Subexpressions](https://www.nushell.sh/book/variables_and_subexpressions.html#subexpressions)
39
+
40
+ ## Semicolons
41
+
42
+ Take this example:
43
+
44
+ ```nu
45
+ > line1; line2 | line3
46
+ ```
47
+
48
+ Here, semicolons are used in conjunction with pipelines. When a semicolon is used, no output data is produced to be piped. As such, the `$in` variable will not work when used immediately after the semicolon.
49
+
50
+ - As there is a semicolon after `line1`, the command will run to completion and get displayed on the screen.
51
+ - `line2` | `line3` is a normal pipeline. It runs, and its contents are displayed after `line1`'s contents.
52
+
53
+ ## Working with external commands
54
+
55
+ Nu commands communicate with each other using the Nu data types (see [types of data](types_of_data.md)), but what about commands outside of Nu? Let's look at some examples of working with external commands:
56
+
57
+ `internal_command | external_command`
58
+
59
+ Data will flow from the internal_command to the external_command. This data will get converted to a string, so that they can be sent to the `stdin` of the external_command.
60
+
61
+ `external_command | internal_command`
62
+
63
+ Data coming from an external command into Nu will come in as bytes that Nushell will try to automatically convert to UTF-8 text. If successful, a stream of text data will be sent to internal_command. If unsuccessful, a stream of binary data will be sent to internal command. Commands like [`lines`](/commands/docs/lines.md) help make it easier to bring in data from external commands, as it gives discrete lines of data to work with.
64
+
65
+ `external_command_1 | external_command_2`
66
+
67
+ Nu works with data piped between two external commands in the same way as other shells, like Bash would. The `stdout` of external_command_1 is connected to the `stdin` of external_command_2. This lets data flow naturally between the two commands.
68
+
69
+ ## Behind the scenes
70
+
71
+ You may have wondered how we see a table if [`ls`](/commands/docs/ls.md) is an input and not an output. Nu adds this output for us automatically using another command called [`table`](/commands/docs/table.md). The [`table`](/commands/docs/table.md) command is appended to any pipeline that doesn't have an output. This allows us to see the result.
72
+
73
+ In effect, the command:
74
+
75
+ ```nu
76
+ > ls
77
+ ```
78
+
79
+ And the pipeline:
80
+
81
+ ```nu
82
+ > ls | table
83
+ ```
84
+
85
+ Are one and the same.
86
+
87
+ > **Note**
88
+ > the sentence _are one and the same_ above only applies for the graphical output in the shell,
89
+ > it does not mean the two data structures are them same
90
+ >
91
+ > ```nushell
92
+ > > (ls) == (ls | table)
93
+ > false
94
+ > ```
95
+ >
96
+ > `ls | table` is not even structured data!
97
+
98
+ ## Output result to external commands
99
+
100
+ Sometimes you want to output Nushell structured data to an external command for further processing. However, Nushell's default formatting options for structured data may not be what you want.
101
+ For example, you want to find a file named "tutor" under "/usr/share/vim/runtime" and check its ownership
102
+
103
+ ```nu
104
+ > ls /usr/share/nvim/runtime/
105
+ ╭────┬───────────────────────────────────────┬──────┬─────────┬───────────────╮
106
+ │ # │ name │ type │ size │ modified │
107
+ ├────┼───────────────────────────────────────┼──────┼─────────┼───────────────┤
108
+ │ 0 │ /usr/share/nvim/runtime/autoload │ dir │ 4.1 KB │ 2 days ago │
109
+ ..........
110
+ ..........
111
+ ..........
112
+
113
+ │ 31 │ /usr/share/nvim/runtime/tools │ dir │ 4.1 KB │ 2 days ago │
114
+ │ 32 │ /usr/share/nvim/runtime/tutor │ dir │ 4.1 KB │ 2 days ago │
115
+ ├────┼───────────────────────────────────────┼──────┼─────────┼───────────────┤
116
+ │ # │ name │ type │ size │ modified │
117
+ ╰────┴───────────────────────────────────────┴──────┴─────────┴───────────────╯
118
+ ```
119
+
120
+ You decided to use `grep` and [pipe](https://www.nushell.sh/book/pipelines.html) the result to external `^ls`
121
+
122
+ ```nu
123
+ > ls /usr/share/nvim/runtime/ | get name | ^grep tutor | ^ls -la $in
124
+ ls: cannot access ''$'\342\224\202'' 32 '$'\342\224\202'' /usr/share/nvim/runtime/tutor '$'\342\224\202\n': No such file or directory
125
+ ```
126
+
127
+ What's wrong? Nushell renders lists and tables (by adding a border with characters like `╭`,`─`,`┬`,`╮`) before piping them as text to external commands. If that's not the behavior you want, you must explicitly convert the data to a string before piping it to an external. For example, you can do so with [`to text`](/commands/docs/to_text.md):
128
+
129
+ ```nu
130
+ > ls /usr/share/nvim/runtime/ | get name | to text | ^grep tutor | tr -d '\n' | ^ls -la $in
131
+ total 24
132
+ drwxr-xr-x@ 5 pengs admin 160 14 Nov 13:12 .
133
+ drwxr-xr-x@ 4 pengs admin 128 14 Nov 13:42 en
134
+ -rw-r--r--@ 1 pengs admin 5514 14 Nov 13:42 tutor.tutor
135
+ -rw-r--r--@ 1 pengs admin 1191 14 Nov 13:42 tutor.tutor.json
136
+ ```
137
+
138
+ (Actually, for this simple usage you can just use [`find`](/commands/docs/find.md))
139
+
140
+ ```nu
141
+ > ls /usr/share/nvim/runtime/ | get name | find tutor | ^ls -al $in
142
+ ```
143
+
144
+ ## Command Output in Nushell
145
+
146
+ Unlike external commands, Nushell commands are akin to functions. Most Nushell commands do not print anything to `stdout` and instead just return data.
147
+
148
+ ```nu
149
+ > do { ls; ls; ls; "What?!" }
150
+ ```
151
+
152
+ This means that the above code will not display the files under the current directory three times.
153
+ In fact, running this in the shell will only display `"What?!"` because that is the value returned by the `do` command in this example. However, using the system `^ls` command instead of `ls` would indeed print the directory thrice because `^ls` does print its result once it runs.
154
+
155
+ Knowing when data is displayed is important when using configuration variables that affect the display output of commands such as `table`.
156
+
157
+ ```nu
158
+ > do { $env.config.table.mode = none; ls }
159
+ ```
160
+
161
+ For instance, the above example sets the `$env.config.table.mode` configuration variable to `none`, which causes the `table` command to render data without additional borders. However, as it was shown earlier, the command is effectively equivalent to
162
+
163
+ ```nu
164
+ > do { $env.config.table.mode = none; ls } | table
165
+ ```
166
+
167
+ Because Nushell `$env` variables are [scoped](https://www.nushell.sh/book/environment.html#scoping), this means that the `table` command in the example is not affected by the
168
+ environment modification inside the `do` block and the data will not be shown with the applied configuration.
169
+
170
+ When displaying data early is desired, it is possible to explicitly apply `| table` inside the scope, or use the `print` command.
171
+
172
+ ```nu
173
+ > do { $env.config.table.mode = none; ls | table }
174
+ > do { $env.config.table.mode = none; print (ls) }
175
+ ```
plugins.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Plugins
2
+
3
+ Nu can be extended using plugins. Plugins behave much like Nu's built-in commands, with the added benefit that they can be added separately from Nu itself.
4
+
5
+ Nu plugins are executables; Nu launches them as needed and communicates with them over [stdin, stdout, and stderr](https://en.wikipedia.org/wiki/Standard_streams). Nu plugins can use either JSON or MSGPACK as their communication encoding.
6
+
7
+ ## Adding a plugin
8
+
9
+ To add a plugin, call the [`register`](/commands/docs/register.md) command to tell Nu where to find it. As you do, you'll need to also tell Nushell what encoding the plugin uses.
10
+
11
+ Please note that the plugin name needs to start with `nu_plugin_`, Nu uses the name prefix to detect plugins.
12
+
13
+ Linux+macOS:
14
+
15
+ ```nu
16
+ > register ./my_plugins/nu_plugin_cool
17
+ ```
18
+
19
+ Windows:
20
+
21
+ ```nu
22
+ > register .\my_plugins\nu_plugin_cool.exe
23
+ ```
24
+
25
+ When [`register`](/commands/docs/register.md) is called:
26
+
27
+ 1. Nu launches the plugin, and waits for the plugin to tell Nu which communication encoding it should use
28
+ 2. Nu sends it a "Signature" message over stdin
29
+ 3. The plugin responds via stdout with a message containing its signature (name, description, arguments, flags, and more)
30
+ 4. Nu saves the plugin signature in the file at `$nu.plugin-path`, so registration is persisted across multiple launches
31
+
32
+ Once registered, the plugin is available as part of your set of commands:
33
+
34
+ ```nu
35
+ > help commands | where command_type == "plugin"
36
+ ```
37
+
38
+ ## Examples
39
+
40
+ Nu's main repo contains example plugins that are useful for learning how the plugin protocol works:
41
+
42
+ - [Rust](https://github.com/nushell/nushell/tree/main/crates/nu_plugin_example)
43
+ - [Python](https://github.com/nushell/nushell/blob/main/crates/nu_plugin_python)
44
+
45
+ ## Debugging
46
+
47
+ The simplest way to debug a plugin is to print to stderr; plugins' standard error streams are redirected through Nu and displayed to the user.
48
+
49
+ ## Help
50
+
51
+ Nu's plugin documentation is a work in progress. If you're unsure about something, the #plugins channel on [the Nu Discord](https://discord.gg/NtAbbGn) is a great place to ask questions!
52
+
53
+ ## More details
54
+
55
+ The [plugin chapter in the contributor book](/contributor-book/plugins.md) offers more details on the intricacies of how plugins work from a software developer point of view.
programming_in_nu.md ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Programming in Nu
2
+
3
+ This chapter goes into more detail of Nushell as a programming language.
4
+ Each major language feature has its own section.
5
+
6
+ Just like most programming languages allow you to define functions, Nushell uses [custom commands](custom_commands.md) for this purpose.
7
+
8
+ From other shells you might be used to [aliases](aliases.md).
9
+ Nushell's aliases work in a similar way and are a part of the programming language, not just a shell feature.
10
+
11
+ Common operations can, such as addition or regex search, be done with [operators](operators.md).
12
+ Not all operations are supported for all data types and Nushell will make sure to let you know.
13
+
14
+ You can store intermediate results to [variables](variables_and_subexpressions.md) and immediately evaluate subroutines with [subexpressions](variables_and_subexpressions.html#subexpressions).
15
+
16
+ The last three sections are aimed at organizing your code:
17
+
18
+ [Scripts](scripts.md) are the simplest form of code organization: You just put the code into a file and source it.
19
+ However, you can also run scripts as standalone programs with command line signatures using the "special" `main` command.
20
+
21
+ With [modules](modules.md), just like in many other programming languages, it is possible to compose your code from smaller pieces.
22
+ Modules let you define a public interface vs. private commands and you can import custom commands, aliases, and environment variables from them.
23
+
24
+ [Overlays](overlays.md) build on top of modules.
25
+ By defining an overlay, you bring in module's definitions into its own swappable "layer" that gets applied on top of other overlays.
26
+ This enables features like activating virtual environments or overriding sets of default commands with custom variants.
27
+
28
+ The help message of some built-in commands shows a [signature](command_signature.md). You can take a look at it to get general rules how the command can be used.
29
+
30
+ The standard library also has a [testing framework](testing.md) if you want to prove your reusable code works perfectly.
quick_tour.md ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Quick Tour
2
+
3
+ The easiest way to see what Nu can do is to start with some examples, so let's dive in.
4
+
5
+ The first thing you'll notice when you run a command like [`ls`](/commands/docs/ls.md) is that instead of a block of text coming back, you get a structured table.
6
+
7
+ @[code](@snippets/introduction/ls_example.sh)
8
+
9
+ The table does more than show the directory in a different way. Just like tables in a spreadsheet, this table allows us to work with the data more interactively.
10
+
11
+ The first thing we'll do is to sort our table by size. To do this, we'll take the output from [`ls`](/commands/docs/ls.md) and feed it into a command that can sort tables based on the contents of a column.
12
+
13
+ @[code](@snippets/introduction/ls_sort_by_reverse_example.sh)
14
+
15
+ You can see that to make this work we didn't pass commandline arguments to [`ls`](/commands/docs/ls.md). Instead, we used the [`sort-by`](/commands/docs/sort-by.md) command that Nu provides to do the sorting of the output of the [`ls`](/commands/docs/ls.md) command. To see the biggest files on top, we also used [`reverse`](/commands/docs/reverse.md).
16
+
17
+ Nu provides many commands that can work on tables. For example, we could use [`where`](/commands/docs/where.md) to filter the contents of the [`ls`](/commands/docs/ls.md) table so that it only shows files over 1 kilobyte:
18
+
19
+ @[code](@snippets/introduction/ls_where_example.sh)
20
+
21
+ Just as in the Unix philosophy, being able to have commands talk to each other gives us ways to mix-and-match in many different combinations. Let's look at a different command:
22
+
23
+ @[code](@snippets/introduction/ps_example.sh)
24
+
25
+ You may be familiar with the [`ps`](/commands/docs/ps.md) command if you've used Linux. With it, we can get a list of all the current processes that the system is running, what their status is, and what their name is. We can also see the CPU load for the processes.
26
+
27
+ What if we wanted to show the processes that were actively using the CPU? Just like we did with the [`ls`](/commands/docs/ls.md) command earlier, we can also work with the table that the [`ps`](/commands/docs/ps.md) command gives back to us:
28
+
29
+ @[code](@snippets/introduction/ps_where_example.sh)
30
+
31
+ So far, we've been using [`ls`](/commands/docs/ls.md) and [`ps`](/commands/docs/ps.md) to list files and processes. Nu also offers other commands that can create tables of useful information. Next, let's explore [`date`](/commands/docs/date.md) and [`sys`](/commands/docs/sys.md).
32
+
33
+ Running [`date now`](/commands/docs/date_now.md) gives us information about the current day and time:
34
+
35
+ @[code](@snippets/introduction/date_example.sh)
36
+
37
+ To get the date as a table we can feed it into [`date to-table`](/commands/docs/date_to-table.md)
38
+
39
+ @[code](@snippets/introduction/date_table_example.sh)
40
+
41
+ Running [`sys`](/commands/docs/sys.md) gives information about the system that Nu is running on:
42
+
43
+ @[code](@snippets/introduction/sys_example.sh)
44
+
45
+ This is a bit different than the tables we saw before. The [`sys`](/commands/docs/sys.md) command gives us a table that contains structured tables in the cells instead of simple values. To take a look at this data, we need to _get_ the column to view:
46
+
47
+ @[code](@snippets/introduction/sys_get_example.sh)
48
+
49
+ The [`get`](/commands/docs/get.md) command lets us jump into the contents of a column of the table. Here, we're looking into the "host" column, which contains information about the host that Nu is running on. The name of the OS, the hostname, the CPU, and more. Let's get the name of the users on the system:
50
+
51
+ @[code](@snippets/introduction/sys_get_nested_example.sh)
52
+
53
+ Right now, there's just one user on the system named "jt". You'll notice that we can pass a column path (the `host.sessions.name` part) and not just the name of the column. Nu will take the column path and go to the corresponding bit of data in the table.
54
+
55
+ You might have noticed something else that's different. Rather than having a table of data, we have just a single element: the string "jt". Nu works with both tables of data as well as strings. Strings are an important part of working with commands outside of Nu.
56
+
57
+ Let's see how strings work outside of Nu in action. We'll take our example from before and run the external [`echo`](/commands/docs/echo.md) command (the `^` tells Nu to not use the built-in [`echo`](/commands/docs/echo.md) command):
58
+
59
+ @[code](@snippets/introduction/sys_get_external_echo_example.sh)
60
+
61
+ If this looks very similar to what we had before, you have a keen eye! It is similar, but with one important difference: we've called `^echo` with the value we saw earlier. This allows us to pass data out of Nu into [`echo`](/commands/docs/echo.md) (or any command outside of Nu, like `git` for example).
62
+
63
+ ### Getting Help
64
+
65
+ Help text for any of Nu's built-in commands can be discovered with the [`help`](/commands/docs/help.md) command. To see all commands, run [`help commands`](/commands/docs/help_commands.md). You can also search for a topic by doing `help -f <topic>`.
66
+
67
+ @[code](@snippets/introduction/help_example.sh)
regular_expressions.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Regular expressions
2
+
3
+ Regular expressions in Nushell's commands are handled by the `rust-lang/regex` crate. If you want to know more, check the crate documentation: "[regex](https://github.com/rust-lang/regex)".
scripts.md ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Scripts
2
+
3
+ In Nushell, you can write and run scripts in the Nushell language. To run a script, you can pass it as an argument to the `nu` commandline application:
4
+
5
+ ```nu
6
+ > nu myscript.nu
7
+ ```
8
+
9
+ This will run the script to completion in a new instance of Nu. You can also run scripts inside the _current_ instance of Nu using [`source`](/commands/docs/source.md):
10
+
11
+ ```nu
12
+ > source myscript.nu
13
+ ```
14
+
15
+ Let's look at an example script file:
16
+
17
+ ```nu
18
+ # myscript.nu
19
+ def greet [name] {
20
+ ["hello" $name]
21
+ }
22
+
23
+ greet "world"
24
+ ```
25
+
26
+ A script file defines the definitions for custom commands as well as the main script itself, which will run after the custom commands are defined.
27
+
28
+ In the above, first `greet` is defined by the Nushell interpreter. This allows us to later call this definition. We could have written the above as:
29
+
30
+ ```nu
31
+ greet "world"
32
+
33
+ def greet [name] {
34
+ ["hello" $name]
35
+ }
36
+ ```
37
+
38
+ There is no requirement that definitions have to come before the parts of the script that call the definitions, allowing you to put them where you feel comfortable.
39
+
40
+ ## How scripts are processed
41
+
42
+ In a script, definitions run first. This allows us to call the definitions using the calls in the script.
43
+
44
+ After the definitions run, we start at the top of the script file and run each group of commands one after another.
45
+
46
+ ## Script lines
47
+
48
+ To better understand how Nushell sees lines of code, let's take a look at an example script:
49
+
50
+ ```nu
51
+ a
52
+ b; c | d
53
+ ```
54
+
55
+ When this script is run, Nushell will first run the `a` command to completion and view its results. Next, Nushell will run `b; c | d` following the rules in the ["Semicolons" section](pipelines.html#semicolons).
56
+
57
+ ## Parameterizing Scripts
58
+
59
+ Script files can optionally contain a special "main" command. `main` will be run after any other Nu code, and is primarily used to add parameters to scripts. You can pass arguments to scripts after the script name (`nu <script name> <script args>`).
60
+
61
+ For example:
62
+
63
+ ```nu
64
+ # myscript.nu
65
+
66
+ def main [x: int] {
67
+ $x + 10
68
+ }
69
+ ```
70
+
71
+ ```nu
72
+ > nu myscript.nu 100
73
+ 110
74
+ ```
75
+
76
+ ## Argument Type Interpretation
77
+
78
+ By default, arguments provided to a script are interpreted with the type `Type::Any`, implying that they are not constrained to a specific data type and can be dynamically interpreted as fitting any of the available data types during script execution.
79
+
80
+ In the previous example, `main [x: int]` denotes that the argument x should possess an integer data type. However, if arguments are not explicitly typed, they will be parsed according to their apparent data type.
81
+
82
+ For example:
83
+
84
+ ```nu
85
+ # implicit_type.nu
86
+ def main [x] {
87
+ $"Hello ($x | describe) ($x)"
88
+ }
89
+
90
+ # explicit_type.nu
91
+ def main [x: string] {
92
+ $"Hello ($x | describe) ($x)"
93
+ }
94
+ ```
95
+
96
+ ```nu
97
+ > nu implicit_type.nu +1
98
+ Hello int 1
99
+
100
+ > nu explicit_type.nu +1
101
+ Hello string +1
102
+ ```
103
+
104
+ ## Subcommands
105
+
106
+ A script can have multiple sub-commands like `run`, `build`, etc. which allows to execute a specific main sub-function. The important part is to expose them correctly with `def main [] {}`. See more details in the [Custom Command](custom_commands.html#sub-commands) section.
107
+
108
+ For example:
109
+
110
+ ```nu
111
+ # myscript.nu
112
+ def "main run" [] {
113
+ print "running"
114
+ }
115
+
116
+ def "main build" [] {
117
+ print "building"
118
+ }
119
+
120
+ # important for the command to be exposed to the outside
121
+ def main [] {}
122
+ ```
123
+
124
+ ```nu
125
+ > nu myscript.nu build
126
+ building
127
+ > nu myscript.nu run
128
+ running
129
+ ```
130
+
131
+ ## Shebangs (`#!`)
132
+
133
+ On Linux and macOS you can optionally use a [shebang](<https://en.wikipedia.org/wiki/Shebang_(Unix)>) to tell the OS that a file should be interpreted by Nu. For example, with the following in a file named `myscript`:
134
+
135
+ ```nu
136
+ #!/usr/bin/env nu
137
+ "Hello World!"
138
+ ```
139
+
140
+ ```nu
141
+ > ./myscript
142
+ Hello World!
143
+ ```
144
+ For script to have access to standard input, `nu` should be invoked with `--stdin` flag:
145
+ ```nu
146
+ #!/usr/bin/env -S nu --stdin
147
+ echo $"stdin: ($in)"
148
+ ```
149
+
150
+ ```nu
151
+ > echo "Hello World!" | ./myscript
152
+ stdin: Hello World!
153
+ ```
shells_in_shells.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Shells in shells
2
+
3
+ ## Working in multiple directories
4
+
5
+ While it's common to work in one directory, it can be handy to work in multiple places at the same time. For this, Nu offers the concept of "shells". As the name implies, they're a way of running multiple shells in one, allowing you to quickly jump between working directories and more.
6
+
7
+ To get started, let's enter a directory:
8
+
9
+ ```nu
10
+ /home/jonathan/Source/nushell(main)> enter ../book
11
+ /home/jonathan/Source/book(main)> ls
12
+ ────┬────────────────────┬──────┬────────┬─────────────
13
+ # │ name │ type │ size │ modified
14
+ ────┼────────────────────┼──────┼────────┼─────────────
15
+ 0 │ 404.html │ File │ 429 B │ 2 hours ago
16
+ 1 │ CONTRIBUTING.md │ File │ 955 B │ 2 hours ago
17
+ 2 │ Gemfile │ File │ 1.1 KB │ 2 hours ago
18
+ 3 │ Gemfile.lock │ File │ 6.9 KB │ 2 hours ago
19
+ ```
20
+
21
+ Entering is similar to changing directories (as we saw with the [`cd`](/commands/docs/cd.md) command). This allows you to jump into a directory to work in it. Instead of changing the directory, we now are in two directories. To see this more clearly, we can use the [`shells`](/commands/docs/shells.md) command to list the current directories we have active:
22
+
23
+ ```nu
24
+ /home/jonathan/Source/book(main)> enter ../music
25
+ /home/jonathan/Source/music(main)> shells
26
+ ───┬────────┬───────────────────────────────
27
+ # │ active │ path
28
+ ───┼────────┼───────────────────────────────
29
+ 0 │ false │ /home/jonathan/Source/nushell
30
+ 1 │ false │ /home/jonathan/Source/book
31
+ 2 │ true │ /home/jonathan/Source/music
32
+ ───┴────────┴───────────────────────────────
33
+ ```
34
+
35
+ The [`shells`](/commands/docs/shells.md) command shows us there are three shells: our original "nushell" source directory, "book" directory and "music" directory which is currently active.
36
+
37
+ We can jump between these shells with the [`n`](/commands/docs/n.md), [`p`](/commands/docs/p.md) and [`g`](/commands/docs/g.md) shortcuts, short for "next", "previous" and "goto":
38
+
39
+ ```nu
40
+ /home/jonathan/Source/music(main)> p
41
+ /home/jonathan/Source/book(main)> n
42
+ /home/jonathan/Source/music(main)> g 0
43
+ /home/jonathan/Source/nushell(main)>
44
+ ```
45
+
46
+ We can see the directory changing, but we're always able to get back to a previous directory we were working on. This allows us to work in multiple directories in the same session.
47
+
48
+ ## Exiting the shell
49
+
50
+ You can leave a shell you have [`enter`](/commands/docs/enter.md)ed using the `dexit` command.
51
+
52
+ You can always quit Nu, even if multiple shells are active, using `exit`.
standard_library.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Standard library (preview)
2
+
3
+ The standard library is located on the [Git repository](https://github.com/nushell/nushell/tree/main/crates/nu-std). At the moment it is an alpha development stage. You can find more documentation there.