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
  • Categories

    • Bits
    • Bytes
    • Chart
    • Conversions
    • Core
    • Database
    • Dataframe
    • Dataframe Or Lazyframe
    • Date
    • Debug
    • Default
    • Env
    • Experimental
    • Expression
    • Filesystem
    • Filters
    • Formats
    • Generators
    • Hash
    • History
    • Lazyframe
    • Math
    • Misc
    • Network
    • Path
    • Platform
    • Plugin
    • Prompt
    • Random
    • Removed
    • Shells
    • Strings
    • System
    • Viewers

def for core

Define a custom command.

Signature

> def {flags} (def_name) (params) (block)

Flags

  • --env: keep the environment defined inside the command
  • --wrapped: treat unknown flags and arguments as strings (requires ...rest-like parameter in signature)

Parameters

  • def_name: Command name.
  • params: Parameters.
  • block: Body of the definition.

Input/output types:

inputoutput
nothingnothing

Examples

Define a command and run it

> def say-hi [] { echo 'hi' }; say-hi
hi

Define a command and run it with parameter(s)

> def say-sth [sth: string] { echo $sth }; say-sth hi
hi

Set environment variable by call a custom command

> def --env foo [] { $env.BAR = "BAZ" }; foo; $env.BAR
BAZ

cd affects the environment, so '--env' is required to change directory from within a command

> def --env gohome [] { cd ~ }; gohome; $env.PWD == ('~' | path expand)
true

Define a custom wrapper for an external command

> def --wrapped my-echo [...rest] { ^echo ...$rest }; my-echo -e 'spam\tspam'
spamspam

Define a custom command with a type signature. Passing a non-int value will result in an error

> def only_int []: int -> int { $in }; 42 | only_int
42

Notes

This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html