Claude
Skills
Sign in
Back

nushell-pro

Included with Lifetime
$97 forever

Comprehensive Nushell scripting best practices, idioms, security, and code review. Use when writing, reviewing, auditing, or refactoring Nushell (.nu) scripts to ensure they follow idiomatic patterns, naming conventions, proper type annotations, functional style, security best practices, and Nushell's unique design principles. Triggers on tasks involving Nushell scripts, modules, custom commands, pipelines, or any .nu file editing. Also helps convert Bash/POSIX scripts to idiomatic Nushell. Covers the type system, data manipulation, performance optimization, security hardening, script review, and common gotchas.

Design

What this skill does


# Nushell Pro — Best Practices & Security Skill

Write idiomatic, performant, secure, and maintainable Nushell scripts. This skill enforces Nushell conventions, catches security issues, and helps avoid common pitfalls.

## Operating Workflow

Use this sequence whenever writing, reviewing, refactoring, or converting Nushell code:

1. Identify the task type: new script, code review, refactor, Bash conversion, module design, security audit, or debugging.
2. Read the existing `.nu` files and nearby project conventions before changing code.
3. Load only the reference files needed for the task:
   - String quoting, interpolation, escaping, regex, or globs -> [String Formats](references/string-formats.md)
   - Security, untrusted input, external commands, paths, credentials, or destructive operations -> [Security](references/security.md)
   - Review-only requests -> [Script Review](references/script-review.md)
   - Bash/POSIX conversion -> [Bash to Nushell](references/bash-to-nushell.md)
   - Modules, exports, scripts, or tests -> [Modules & Scripts](references/modules-and-scripts.md)
   - Types, records, tables, lists, or conversions -> [Data & Type System](references/data-and-types.md)
   - Streaming, `peek`, `parse`, `par-each`, performance, closures, or version-sensitive command behavior -> [Advanced Patterns](references/advanced-patterns.md)
   - Large datasets, Polars dataframes, columnar analytics, heavy group-by/join -> [Dataframes](references/dataframes.md)
   - Common mistakes and fixes -> [Anti-Patterns](references/anti-patterns.md)
4. Apply the critical checks in this file first, then use references for details.
5. Validate parseability with `nu -c 'source path/to/file.nu'` for modules or `nu path/to/script.nu` for scripts when the command is safe to run.
6. Summarize security findings first, then correctness/style/performance changes.

If validation fails -> read the Nushell diagnostic, fix the syntax or type signature, and rerun the smallest safe validation command.
If a command has side effects -> validate only parseability or use a fixture/temp directory.
If a reference conflicts with local project style -> keep project style unless it violates safety, parseability, or Nushell semantics.

STOP CHECKPOINT: Before approving code that runs external commands, deletes files, reads credentials, mutates `$env`, or executes user-provided paths/patterns, explicitly confirm the safe argument boundaries and failure behavior.

## Core Principles

1. **Think in pipelines** — Data flows through pipelines; prefer functional transformations over imperative loops
2. **Immutability first** — Use `let` by default; only use `mut` when functional alternatives don't apply
3. **Structured data** — Nushell works with tables, records, and lists natively; leverage structured data over string parsing
4. **Static parsing** — All code is parsed before execution; `source`/`use` require parse-time constants
5. **Implicit return** — The last expression's value is the return value; no need for `echo` or `return`
6. **Scoped environment** — Environment changes are local to their block; use `def --env` when caller-side changes are needed
7. **Type safety** — Annotate parameter types and input/output signatures for better error detection and documentation
8. **Prefer `match` for branching** — Use `match` instead of long `if`/`else if` chains when dispatching on one value or handling many branches
9. **Parallel ready** — Immutable code enables easy `par-each` parallelization

## Critical: Pipeline Input vs Parameters

**Pipeline input (`$in`) is NOT interchangeable with function parameters!**

```nu
# WRONG — treats pipeline data as first parameter
def my-func [items: list, value: any] {
    $items | append $value
}

# CORRECT — declares pipeline signature
def my-func [value: any]: list -> list {
    $in | append $value
}

# Usage
[1 2 3] | my-func 4  # Works correctly
```

**Why this matters:**

- Pipeline input can be **lazily evaluated** (streaming)
- Parameters are **eagerly evaluated** (loaded into memory)
- Different calling conventions entirely — `$list | func arg` vs `func $list arg`

### Type signature forms

```nu
def func [x: int] { ... }                    # params only
def func []: string -> int { ... }           # pipeline only
def func [x: int]: string -> int { ... }     # both pipeline and params
def func []: [list -> list, string -> list] { ... }  # multiple I/O types
```

## Naming Conventions

| Entity           | Convention             | Example                              |
| ---------------- | ---------------------- | ------------------------------------ |
| Commands         | `kebab-case`           | `fetch-user`, `build-all`            |
| Subcommands      | `kebab-case`           | `"str my-cmd"`, `date list-timezone` |
| Flags            | `kebab-case`           | `--all-caps`, `--output-dir`         |
| Variables/Params | `snake_case`           | `$user_id`, `$file_path`             |
| Environment vars | `SCREAMING_SNAKE_CASE` | `$env.APP_VERSION`                   |
| Constants        | `snake_case`           | `const max_retries = 3`              |

- Prefer full words over abbreviations unless widely known (`url` ok, `usr` not ok)
- Flag variable access replaces dashes with underscores: `--all-caps` -> `$all_caps`

## Formatting Rules

### One-line format (default for short expressions)

```nu
[1 2 3] | each {|x| $x * 2 }
{name: 'Alice', age: 30}
```

### Multi-line format (scripts, >80 chars, nested structures)

```nu
[1 2 3 4] | each {|x|
    $x * 2
}

[
    {name: 'Alice', age: 30}
    {name: 'Bob', age: 25}
]
```

### Spacing rules

- One space before and after `|`
- No space before `|params|` in closures: `{|x| ...}` not `{ |x| ...}`
- One space after `:` in records: `{x: 1}` not `{x:1}`
- Omit commas in lists: `[1 2 3]` not `[1, 2, 3]`
- No trailing spaces
- One space after `,` when used (closure params, etc.)

## Custom Commands Best Practices

### Type annotations and I/O signatures

```nu
# Fully typed with I/O signature
def add-prefix [text: string, --prefix (-p): string = 'INFO']: nothing -> string {
    $'($prefix): ($text)'
}

# Multiple I/O signatures
def to-list []: [
    list -> list
    string -> list
] {
    # implementation
}
```

### Documentation with comments and attributes

```nu
# Fetch user data from the API
#
# Retrieves user information by ID and returns
# a structured record with all available fields.
@example 'Fetch user by ID' { fetch-user 42 }
@category 'network'
def fetch-user [
    id: int           # The user's unique identifier
    --verbose (-v)    # Show detailed request info
]: nothing -> record {
    # implementation
}
```

### Parameter guidelines

- Maximum 2 positional parameters; use flags for the rest
- Provide both long and short flag names: `--output (-o): string`
- Use default values: `def greet [name: string = 'World']`
- Use `?` for optional positional params: `def greet [name?: string]`
- Use rest params for variadic input: `def multi-greet [...names: string]`
- Use `def --wrapped` to wrap external commands and forward unknown flags

### Calling commands with named flags

Keep short custom command calls with named flags on one line. If the invocation
must span lines, wrap the whole command in parentheses so the continuation is
explicit. A bare newline can terminate the command, leaving following `--flags`
as separate statements that produce plain output or parse errors.

```nu
# Prefer for short calls
build-report $target --format json --strict

# Good — explicit multiline invocation
let report = (
    build-report $target
        --format json
        --strict
)

# Bad — flags start new statements
build-report $target
--format json
--strict
```

### Environment-modifying commands

```nu
def --env setup-project [] {
    cd project-dir
    $env.PROJECT_ROOT = (pwd)
}
```

## Data Manipulation Patterns

### Working with records

```nu
{name: 'Alice', age: 30}          # Create record
$rec1 | merg
Files: 13
Size: 124.3 KB
Complexity: 61/100
Category: Design

Related in Design