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 mainwith typed parameters. - Help: limit the script header to its purpose and operating constraints, and document usage at each command and parameter so
--helpcarries 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 readandindex read. Otherwise list the imported commands, as inuse ./paths.nu [path-split path-label], so a reader sees where each name comes from. A test mayuse ./<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-dirbecause 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 dedentfromstd-rfc/stron the next line and any enclosing parenthesis on its own line.
Paths
- Path joins: pass a literal relative path to
path joinas one/-separated string, as inpath 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 selfruns only at parse time and names the file it appears in, while$env.FILE_PWDand$env.CURRENT_FILEpoint 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 != beforecompares theaftercolumn with the string"before"(writewhere 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 withand ($b)calls a command namedand, so wrap the whole expression in parentheses.
Data and types
Input formats
- `from json` accepts some plain text, so `try` cannot validate JSON.
openon 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.renderedin the catch block, since$e.msggives only a generic parsing or scanning message. - `open --raw` yields a byte stream, which collects to `binary` on invalid UTF-8, so a
: stringparameter or astring ->input raises a type error. To require UTF-8, pipe the stream itself intointo stringinsidetry, which raisesNon-UTF8 stringon invalid bytes and on a UTF-16 BOM. Materialize the result into aletbinding orcollectinsidetrybefore streaming intolines, which otherwise replaces invalid UTF-8 withU+FFFD.into stringrejects every collectedbinary, 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
trywhen 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
-> recordfunction can return a list from an untyped helper, andget -oon an empty list returns[], whichdefaultkeeps. A body that ends in a bareerror makeinferserror, so adiehelper declared: nothing -> nothingfails to parse and the script never runs, while one wrapped inif,match, ordopasses. Declare: nothing -> erroror 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 = nullrejects a record,mut n = 0rejects a float, andgenerate {|row, acc = null| ... }raisesCan't convert to nothingonce it passesacca value. Annotate the union, as inmut 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, andselectall do (nushell/nushell#19463), and nushell/nushell#19467 lists the affected commands. The script continues, so only output the closure printed first, such as adiehelper's message, still appears.collectbefore the command surfaces the error. Take a single match withfirst, 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 inupdate 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--allescapes those three as well. To match another encoder, pass only the characters it escapes throughurl encode --all. - `str length` counts UTF-8 bytes by default.
"中文字" | str lengthreturns 9 on the pinned Nushell. Pass--charsor--grapheme-clusterswhen a limit is written in characters.
Arguments
- Forwarding arguments needs `def --wrapped`. A plain
defparses flags in...argsitself.--wrappedalso passes--helpthrough as an argument, so a command whose operands may start with-keeps a plaindefand its callers pass--. - `nu <script> <args>` re-parses the arguments as source text. Nushell rebuilds the
maincall from the arguments, quoting one only when it holds whitespace or a special character such as;or starts with$, so an untypedmainparameter receives8as 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'printsINJECTEDwhenmainaccepts--xor the argument follows--), a bare redirection token ('o>' out.txtsendsmain's output toout.txt, truncating it even whenmainonly prints), and an argument starting with...$('...$env.PATH'spreadsPATHinto 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-flagvalues precede caller arguments, and Nushell accepts later overrides, including--switch=false. Values that a documented constraint makes immutable belong inmakeWrapper --setenvironment variables. - A flag on `def main` does not reach `def "main <sub>"`.
script sub --flagfails with an unknown flag, andscript --flag subpassessubtomainas 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
^cpwhen 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| completeand checking.exit_code. Piping intoignorediscards the exit status along with the output, so after^cmd | ignorethe script continues and can exit 0. - `$in` is empty under a shebang without `--stdin`. Use
^catwhen that flag is absent. On Linux, reopening/dev/stdinfails with ENXIO on a socket. Text capture strips one trailing newline, so use^cat | into binaryfor 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 insidewith-env {HOME: ...}in the same process reads$env.HOME. A child Nushell started with a newHOMEsees 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 jsonfor JSON orto json --rawper 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
mktempdirectory 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\nfor line breaks in single-line strings.
Preview shortened. The full SKILL.md is in the pack.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 13.0 kB | f10a9b7840f8 |
| SKILVAULT_SOURCE.json | 1.2 kB | 04ede59d9f2a |
| THIRD_PARTY_NOTICES.md | 1.1 kB | 0d928389ea10 |
| agents/openai.yaml | 204 B | 2ae07638986a |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 0.1.0 Current | a04feb174531 | 29 Nov 2026 |
Locking a skill to one version needs Pro.