Home Explore Blog CI



nushell

3rd chunk of `book/cheat_sheet.md`
8e575450c314942383d9981709a51c982a17a60f9cf25fd40000000100000abe
$a | append $b
# => ╭───┬──────────────┬───────────────┬──────────────╮
# => │ # │ first_column │ second_column │ third_column │
# => ├───┼──────────────┼───────────────┼──────────────┤
# => │ 0 │ foo          │ bar           │ snooze       │
# => │ 1 │ hex          │ seeze         │ feeze        │
# => ╰───┴──────────────┴───────────────┴──────────────╯
```

remove the last column of a table:

```nu
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:

```nu
start file.txt
```

save a string to text file:

```nu
'lorem ipsum ' | save file.txt
```

append a string to the end of a text file:

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

save a record to file.json:

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

recursively search for files by file name:

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

watch a file, run command whenever it changes:

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

## Custom Commands

custom command with parameter type set to string:

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

custom command with default parameter set to nushell:

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

passing named parameter by defining flag for custom commands:

```nu
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:

```nu
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:

```nu
def greet [...name: string] {
    print "hello all:"
    for $n in $name {
        print $n

Title: Nushell Cheat Sheet: File Operations and Custom Commands
Summary
This section covers appending tables, removing columns from tables, opening and saving files (including appending to existing files and saving JSON), recursively searching for files using glob patterns, and watching files for changes to trigger commands. It also provides examples of defining custom commands with typed parameters, default parameters, named parameters (flags), switch flags, and rest parameters for accepting any number of positional arguments.