Nushell
Get Nu!
Getting Started
  • The Nushell Book
  • Command Reference
  • Cookbook
  • Language Reference Guide
  • Contributing Guide
Blog
  • English
  • 中文
  • Deutsch
  • Français
  • Español
  • 日本語
  • Português do Brasil
  • Русский язык
GitHub
Get Nu!
Getting Started
  • The Nushell Book
  • Command Reference
  • Cookbook
  • Language Reference Guide
  • Contributing Guide
Blog
  • English
  • 中文
  • Deutsch
  • Français
  • Español
  • 日本語
  • Português do Brasil
  • Русский язык
GitHub
  • Introduction
  • Installation
    • Default Shell
  • Getting Started
    • Quick Tour
    • Moving Around the System
    • Thinking in Nu
    • Nushell Cheat Sheet
  • Nu Fundamentals
    • Types of Data
    • Loading Data
    • Pipelines
    • Working with Strings
    • Working with Lists
    • Working with Records
    • Working with Tables
    • Navigating and Accessing Structured Data
    • Special Variables
  • Programming in Nu
    • Custom Commands
    • Aliases
    • Operators
    • Variables
    • Control Flow
    • Scripts
    • Modules
      • Using Modules
      • Creating Modules
    • Overlays
    • Sorting
    • Testing your Nushell Code
    • Best Practices
  • Nu as a Shell
    • Configuration
    • Environment
    • Stdout, Stderr, and Exit Codes
    • Running System (External) Commands
    • How to Configure 3rd Party Prompts
    • Directory Stack
    • Reedline, Nu's Line Editor
    • Custom Completions
    • Externs
    • Coloring and Theming in Nu
    • Hooks
    • Background Jobs
  • Coming to Nu
    • Coming from Bash
    • Coming from CMD.EXE
    • Nu map from other shells and domain specific languages
    • Nu Map from Imperative Languages
    • Nu Map from Functional Languages
    • Nushell operator map
  • Design Notes
    • How Nushell Code Gets Run
  • (Not So) Advanced
    • Standard Library (Preview)
    • Dataframes
    • Metadata
    • Creating Your Own Errors
    • Parallelism
    • Plugins
    • explore

Nushell Cheat Sheet

Data Types

convert string to integer:

"12" | into int

convert present date to provided time zone:

date now | date to-timezone "Europe/London"

update a record's language and if none is specified insert provided value:

{'name': 'nu', 'stars': 5, 'language': 'Python'} | upsert language 'Rust'

convert list of strings to yaml:

[one two three] | to yaml

print table data:

[[framework, language]; [Django, Python] [Laravel, PHP]]

select two named columns from the table and print their values:

[{name: 'Robert' age: 34 position: 'Designer'}
 {name: 'Margaret' age: 30 position: 'Software Developer'}
 {name: 'Natalie' age: 50 position: 'Accountant'}
] | select name position

Strings

interpolate text:

let name = "Alice"
$"greetings, ($name)!"
# => greetings, Alice!

split text on comma delimiter and save the list to string_list variable:

let string_list = "one,two,three" | split row ","
$string_list
# => ╭───┬───────╮
# => │ 0 │ one   │
# => │ 1 │ two   │
# => │ 2 │ three │
# => ╰───┴───────╯

check if a string contains a substring:

"Hello, world!" | str contains "o, w"
# => true

join multiple strings with delimiter:

let str_list = [zero one two]
$str_list | str join ','
# => zero,one,two

slice text by indices:

'Hello World!' | str substring 4..8
# => o Wor

parse string into named columns:

'Nushell 0.80' | parse '{shell} {version}'
# => ╭───┬─────────┬─────────╮
# => │ # │  shell  │ version │
# => ├───┼─────────┼─────────┤
# => │ 0 │ Nushell │ 0.80    │
# => ╰───┴─────────┴─────────╯

parse comma separated values (csv):

"acronym,long\nAPL,A Programming Language" | from csv
# => ╭───┬─────────┬────────────────────────╮
# => │ # │ acronym │          long          │
# => ├───┼─────────┼────────────────────────┤
# => │ 0 │ APL     │ A Programming Language │
# => ╰───┴─────────┴────────────────────────╯

color text in command-line terminal:

$'(ansi purple_bold)This text is a bold purple!(ansi reset)'
# => This text is a bold purple!

Lists

insert list value at index:

[foo bar baz] | insert 1 'beeze'
# => ╭───┬───────╮
# => │ 0 │ foo   │
# => │ 1 │ beeze │
# => │ 2 │ bar   │
# => │ 3 │ baz   │
# => ╰───┴───────╯

update list value by index:

[1, 2, 3, 4] | update 1 10
# => ╭───┬────╮
# => │ 0 │  1 │
# => │ 1 │ 10 │
# => │ 2 │  3 │
# => │ 3 │  4 │
# => ╰───┴────╯

prepend list value:

let numbers = [1, 2, 3]
$numbers | prepend 0
# => ╭───┬───╮
# => │ 0 │ 0 │
# => │ 1 │ 1 │
# => │ 2 │ 2 │
# => │ 3 │ 3 │
# => ╰───┴───╯

append list value:

let numbers = [1, 2, 3]
$numbers | append 4
# => ╭───┬───╮
# => │ 0 │ 1 │
# => │ 1 │ 2 │
# => │ 2 │ 3 │
# => │ 3 │ 4 │
# => ╰───┴───╯

slice first list values:

[cammomile marigold rose forget-me-not] | first 2
# => ╭───┬───────────╮
# => │ 0 │ cammomile │
# => │ 1 │ marigold  │
# => ╰───┴───────────╯

iterate over a list; elt is current list value:

let planets = [Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune]
$planets | each { |elt| $"($elt) is a planet of the solar system" }
# => ╭───┬─────────────────────────────────────────╮
# => │ 0 │ Mercury is a planet of the solar system │
# => │ 1 │ Venus is a planet of the solar system   │
# => │ 2 │ Earth is a planet of the solar system   │
# => │ 3 │ Mars is a planet of the solar system    │
# => │ 4 │ Jupiter is a planet of the solar system │
# => │ 5 │ Saturn is a planet of the solar system  │
# => │ 6 │ Uranus is a planet of the solar system  │
# => │ 7 │ Neptune is a planet of the solar system │
# => ╰───┴─────────────────────────────────────────╯

iterate over a list with an index and value:

$planets | enumerate | each { |elt| $"($elt.index + 1) - ($elt.item)" }
# => ╭───┬─────────────╮
# => │ 0 │ 1 - Mercury │
# => │ 1 │ 2 - Venus   │
# => │ 2 │ 3 - Earth   │
# => │ 3 │ 4 - Mars    │
# => │ 4 │ 5 - Jupiter │
# => │ 5 │ 6 - Saturn  │
# => │ 6 │ 7 - Uranus  │
# => │ 7 │ 8 - Neptune │
# => ╰───┴─────────────╯

reduce the list to a single value; reduce gives access to accumulator that is applied to each element in the list:

let scores = [3 8 4]
$"total = ($scores | reduce { |elt, acc| $acc + $elt })"
# => total = 15

reduce with an initial value (--fold):

let scores = [3 8 4]
$"total = ($scores | reduce --fold 1 { |elt, acc| $acc * $elt })"
# => total = 96

give access to the 3rd item in the list:

let planets = [Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune]
$planets.2
# => Earth

check if any string in the list starts with E:

let planets = [Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune]
$planets | any {|elt| $elt | str starts-with "E" }
# => true

slice items that satisfy provided condition:

let cond = {|x| $x < 0 }; [-1 -2 9 1] | take while $cond
# => ╭───┬────╮
# => │ 0 │ -1 │
# => │ 1 │ -2 │
# => ╰───┴────╯

Tables

sort table:

ls | sort-by size

sort table, get first rows:

ls | sort-by size | first 5

concatenate two tables with same columns:

let $a = [[first_column second_column third_column]; [foo bar snooze]]
let $b = [[first_column second_column third_column]; [hex seeze feeze]]
$a | append $b
# => ╭───┬──────────────┬───────────────┬──────────────╮
# => │ # │ first_column │ second_column │ third_column │
# => ├───┼──────────────┼───────────────┼──────────────┤
# => │ 0 │ foo          │ bar           │ snooze       │
# => │ 1 │ hex          │ seeze         │ feeze        │
# => ╰───┴──────────────┴───────────────┴──────────────╯

remove the last column of a table:

let teams_scores = [[team score plays]; ['Boston Celtics' 311 3] ['Golden State Warriors', 245 2]]
$teams_scores | drop column
# => ╭───┬───────────────────────┬───────╮
# => │ # │         team          │ score │
# => ├───┼───────────────────────┼───────┤
# => │ 0 │ Boston Celtics        │   311 │
# => │ 1 │ Golden State Warriors │   245 │
# => ╰───┴───────────────────────┴───────╯

Files and Filesystem

open a text file with the default text editor:

start file.txt

save a string to text file:

'lorem ipsum ' | save file.txt

append a string to the end of a text file:

'dolor sit amet' | save --append file.txt

save a record to file.json:

{ a: 1, b: 2 } | save file.json

recursively search for files by file name:

glob **/*.{rs,toml} --depth 2

watch a file, run command whenever it changes:

watch . --glob=**/*.rs {|| cargo test }

Custom Commands

custom command with parameter type set to string:

def greet [name: string] {
    $"hello ($name)"
}

custom command with default parameter set to nushell:

def greet [name = "nushell"] {
    $"hello ($name)"
}

passing named parameter by defining flag for custom commands:

def greet [
    name: string
    --age: int
] {
    [$name $age]
}

greet world --age 10

using flag as a switch with a shorthand flag (-a) for the age:

def greet [
    name: string
    --age (-a): int
    --twice
] {
    if $twice {
        [$name $age $name $age]
    } else {
        [$name $age]
    }
}
greet -a 10 --twice hello

custom command which takes any number of positional arguments using rest params:

def greet [...name: string] {
    print "hello all:"
    for $n in $name {
        print $n
    }
}
greet earth mars jupiter venus
# => hello all:
# => earth
# => mars
# => jupiter
# => venus

Variables

an immutable variable cannot change its value after declaration:

let val = 42
print $val
# => 42

shadowing variable (declaring variable with the same name in a different scope):

let val = 42
do { let val = 101;  $val }
# => 101
$val
# => 42

declaring a mutable variable with mut key word:

mut val = 42
$val += 27
$val
# => 69

closures and nested defs cannot capture mutable variables from their environment (errors):

mut x = 0
[1 2 3] | each { $x += 1 }
# => Error: nu::parser::expected_keyword
# => 
# =>   × Capture of mutable variable.
# =>    ╭─[entry #83:1:18]
# =>  1 │ [1 2 3] | each { $x += 1 }
# =>    ·                  ─┬
# =>    ·                   ╰── capture of mutable variable
# =>    ╰────

a constant variable is immutable and is fully evaluated at parse-time:

const file = 'path/to/file.nu'
source $file

use question mark operator ? to return null instead of error if provided path is incorrect:

let files = (ls)
$files.name?.0?

assign the result of a pipeline to a variable:

let big_files = (ls | where size > 10kb)
$big_files

Modules

use an inline module:

module greetings {
    export def hello [name: string] {
        $"hello ($name)!"
    }

    export def hi [where: string] {
        $"hi ($where)!"
    }
}
use greetings hello
hello "world"

import module from file and use its environment in current scope:

# greetings.nu
export-env {
    $env.MYNAME = "Arthur, King of the Britons"
}
export def hello [] {
    $"hello ($env.MYNAME)"
}

use greetings.nu
$env.MYNAME
# => Arthur, King of the Britons
greetings hello
# => hello Arthur, King of the Britons!

use main command in module:

# greetings.nu
export def hello [name: string] {
    $"hello ($name)!"
}

export def hi [where: string] {
    $"hi ($where)!"
}

export def main [] {
    "greetings and salutations!"
}

use greetings.nu
greetings
# => greetings and salutations!
greetings hello world
# => hello world!
Edit this page on GitHub
Contributors: lomm28, dlamei, Kingalidj, Dave Clausen, Justin Ma, SeerLite, Ian Manske, Devyn Cairns, Jakub Žádník, Stefan Holderbach, Rayan Amal, Jan Klass, monadix, Bruce Weirdan, Hofer-Julian, 0x4D5352, NotTheDr01ds, joshuanussbaum
Prev
Thinking in Nu