Modules

Like many programming languages, Nushell supports writing and using modules as a way to organize code more efficiently. Modules can be thought of as “containers” that hold various definitions, including:

  • Additional custom commands
  • Aliases
  • Constants
  • Externs
  • Environment variables
  • And even other modules (a.k.a., submodules)

Many users will start off using modules written by others, then progress to writing their own. This chapter covers those two topics:

Ported from nushell/nushell.github.io. Copyright (c) 2021 Nushell Project. MIT License.

Tips

Intro

An empty module still has a name.

module demo {}

Another module can be only a name.

module sample {}

Basic

scope modules lists the module you defined.

module demo {}
scope modules | where name == "demo" | length

A second name is found the same way.

module tools {}
scope modules | where name == "tools" | length

Intermediate

Read the name column after the filter.

module demo {}
scope modules | where name == "demo" | get name | length

each can read every module name.

module demo {}
scope modules | each {|m| $m.name} | length

Advanced

Export a greeting and call it by its module name.

module greet {
  export def hello [name: string] {
    $"hi ($name)"
  }
}
use greet
greet hello tips