SkilVaultSign inStart free

Catalogue / nushell

nushell

MITSignedWrite, review, and debug Nushell scripts and tests. Use when a task touches a `.nu` file or Nushell behaves unexpectedly.
---
name: nushell
description: >-
  Write, review, and debug Nushell scripts and tests. Use when a task touches a `.nu` file or
  Nushell behaves unexpectedly.
---

Nushell

Scripts

Entry and help

  • Entry point: def main with typed parameters.
  • Help: limit the script header to its purpose and operating constraints, and document usage at each command and parameter so --help carries it.

Modules and imports

  • Modules: export only what another module or the module's own test calls, and keep other helpers private. Layer modules so imports point one way, with the entry importing domain modules and domain modules importing generic helpers.
  • Imports: import a module by name when its commands share verbs with sibling modules, so calls read like cache read and index read. Otherwise list the imported commands, as in use ./paths.nu [path-split path-label], so a reader sees where each name comes from. A test may use ./<module>.nu *.

Layout and order

  • Order: order a module's sections in the order the entry first calls them, and within a section put callees before callers.
  • Records: write record literals with multiple fields one field per line, including records inside lists.
  • Custom commands: their switches stay on one line, as a builtin's do, since Nushell parses them itself.

Quoting and strings

  • Quoting: quote string values, including paths and path segments, so they read as data.
  • Use double quotes, switching to single quotes when the text holds a literal backslash or double quote, as a regex does. Keep the quotes any word needs to stay a literal string, as in "0700" and "1min".
  • Leave names, flags, subcommands, and a builtin's own words bare, as in decode utf-8. Leave a glob meant to expand bare.
  • Prefer bare fixed numeric modes for external commands, as in chmod 600, because their argument bytes are preserved.
  • Build a home path from $env.HOME? | default $nu.home-dir because a quoted ~ stays literal.
  • Interpolation: prefer native $"...($value)..." to concatenating text and values, and use multiline strings for multiline text. Escape literal parentheses as \( and \) in double-quoted interpolations.
  • Multiline strings: align the opening quote, content, and closing quote at the same column, then place | str dedent from std-rfc/str on the next line and any enclosing parenthesis on its own line.

Paths

  • Path joins: pass a literal relative path to path join as one /-separated string, as in path join "libexec/gnubin", so it reads as the path it names, and give each segment that comes from a variable its own argument.
  • Script-relative paths: locate files beside a script through a named constant at the top, as in const SCRIPT_DIR = path self ".", and join paths onto it. path self runs only at parse time and names the file it appears in, while $env.FILE_PWD and $env.CURRENT_FILE point at the running script even inside a module.

Traps

These traps assume the Nushell Book's Thinking in Nu and Coming from Bash. Reproduce a trap on the pinned Nushell before adding it.

Syntax

  • Bare words depend on context. where after != before compares the after column with the string "before" (write where after != $it.before), and a comma splits a list item, so [--sort=-pcpu,-pmem] holds two items. Inside a list, an operator is a bare word too, so ["a" + $x] holds three elements. Write [("a" + $x)] or [$"a($x)"].
  • Outside parentheses or a list, a newline ends the command. Arguments continue across lines only inside parentheses or a list, binary operators continue only inside parentheses, and a line starting with | continues the pipeline. A line starting with and ($b) calls a command named and, so wrap the whole expression in parentheses.

Data and types

Input formats
  • `from json` accepts some plain text, so `try` cannot validate JSON. open on an empty JSON, YAML, or NUON file returns null, while truncated JSON raises, so check the shape ($j | describe | str starts-with "record") before reading a field.
  • YAML error messages hide the parser's detail. Read $e.rendered in the catch block, since $e.msg gives only a generic parsing or scanning message.
  • `open --raw` yields a byte stream, which collects to `binary` on invalid UTF-8, so a : string parameter or a string -> input raises a type error. To require UTF-8, pipe the stream itself into into string inside try, which raises Non-UTF8 string on invalid bytes and on a UTF-16 BOM. Materialize the result into a let binding or collect inside try before streaming into lines, which otherwise replaces invalid UTF-8 with U+FFFD. into string rejects every collected binary, valid or not.
Types and shapes
  • `get -o` raises on rows that are not records. It tolerates a missing column but fails on a list of strings or a scalar, so wrap it in try when the shape is unverified.
  • Return annotations are checked only at parse time, against the type the parser infers for the body's last expression. A -> record function can return a list from an untyped helper, and get -o on an empty list returns [], which default keeps. A body that ends in a bare error make infers error, so a die helper declared : nothing -> nothing fails to parse and the script never runs, while one wrapped in if, match, or do passes. Declare : nothing -> error or omit the output type.
  • A `mut` or a defaulted closure parameter takes the type of its initial value. Each later value is checked against that type, at parse time when its type is known and at runtime otherwise, so mut current = null rejects a record, mut n = 0 rejects a float, and generate {|row, acc = null| ... } raises Can't convert to nothing once it passes acc a value. Annotate the union, as in mut current: oneof<record, nothing> = null, because a linter misses the runtime case.
Commands
  • A command that pulls a stream item and discards it drops that item's `exit` or `error make`. get <n>, last, skip, drop, and select all do (nushell/nushell#19463), and nushell/nushell#19467 lists the affected commands. The script continues, so only output the closure printed first, such as a die helper's message, still appears. collect before the command surfaces the error. Take a single match with first, which stops pulling once it has one item and returns null on an empty stream.
  • `math sum` errors on an empty list. Use | append 0 | math sum.
  • `into datetime` reads a bare integer as nanoseconds. A Unix timestamp in seconds needs into datetime --format "%s".
  • `update` binds a named closure parameter to the row, not the cell. Read the cell value from $in, as in update body { $in | append $line }.

Strings and arguments

Strings
  • Dynamic regexes can use single-quoted pieces. Parentheses interpolate in both $"..." and $'...', and double quotes consume backslashes, so single-quoted concatenation avoids those escapes: ($label + ' (?<n>\d+)').
  • `url encode` escapes characters a URI keeps. The default escapes every ASCII punctuation mark except ., /, and :, including the unreserved -, _, and ~, and --all escapes those three as well. To match another encoder, pass only the characters it escapes through url encode --all.
  • `str length` counts UTF-8 bytes by default. "中文字" | str length returns 9 on the pinned Nushell. Pass --chars or --grapheme-clusters when a limit is written in characters.
Arguments
  • Forwarding arguments needs `def --wrapped`. A plain def parses flags in ...args itself. --wrapped also passes --help through as an argument, so a command whose operands may start with - keeps a plain def and its callers pass --.
  • `nu <script> <args>` re-parses the arguments as source text. Nushell rebuilds the main call from the arguments, quoting one only when it holds whitespace or a special character such as ; or starts with $, so an untyped main parameter receives 8 as an int. Three shapes stay code on the pinned Nushell (nushell/nushell#19484): the name part of a -- argument before any =, even after a positional ('--x;print INJECTED' prints INJECTED when main accepts --x or the argument follows --), a bare redirection token ('o>' out.txt sends main's output to out.txt, truncating it even when main only prints), and an argument starting with ...$ ('...$env.PATH' spreads PATH into the arguments). Never pass an untrusted string as a script argument. Pass it through stdin, an environment variable, or a file, or check it against an allowlist pattern first.
  • Wrapper-supplied options remain overridable. makeWrapper --add-flag values precede caller arguments, and Nushell accepts later overrides, including --switch=false. Values that a documented constraint makes immutable belong in makeWrapper --set environment variables.
  • A flag on `def main` does not reach `def "main <sub>"`. script sub --flag fails with an unknown flag, and script --flag sub passes sub to main as a positional, so declare a shared flag on each subcommand.

External commands

  • `cp` reports a refused read or write as `nu: <error>` and still succeeds. Use ^cp when that failure must raise an error.
  • A nonzero external exit ends the script with that code without an automatic failure diagnostic. The command's stdout and stderr can still print. Tolerate it with try, or by using | complete and checking .exit_code. Piping into ignore discards the exit status along with the output, so after ^cmd | ignore the script continues and can exit 0.
  • `$in` is empty under a shebang without `--stdin`. Use ^cat when that flag is absent. On Linux, reopening /dev/stdin fails with ENXIO on a socket. Text capture strips one trailing newline, so use ^cat | into binary for byte-identical round trips.

Environment

  • `$nu.home-dir` ignores a `HOME` change inside the running Nushell. It is fixed at startup, so code that runs after $env.HOME = ... or inside with-env {HOME: ...} in the same process reads $env.HOME. A child Nushell started with a new HOME sees it.

Testing

Test a script with std/assert when its output is easy to get subtly wrong. Drive it the way its caller does, and skip tests that only restate the code or require the external tools the script exists to call. Run an entry script through ^$nu.current-exe, which names the running Nushell binary, so the script runs on the same Nushell as its test.

Files and assertions

  • Location: a test sits beside the module or entry script it tests as <name>.test.nu.
  • Assertions: compare the whole shape a test owns in one assert equal, so an unexpected field or row fails it.

Inputs and fixtures

  • Structured inputs: write JSON and JSONL test inputs as Nushell records and lists, serialized with to json for JSON or to json --raw per line for JSONL.
  • Fixtures: keep small structured inputs in the test file. When several cases differ in document-like or byte-sensitive inputs, store them as golden files under the project's fixture directory, copying each input into a mktemp directory before running the script so the script never writes to a fixture.
  • When a fixture directory bundles structured inputs and expected outputs in case.nuon, multiline strings preserve leading indentation as literal content, so start continuation lines at column 0 and use \n for line breaks in single-line strings.

Preview shortened. The full SKILL.md is in the pack.