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
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# Custom commands

Nu's ability to compose long pipelines allows you a lot of control over your data and system, but it comes at the price of a lot of typing. Ideally, you'd be able to save your well-crafted pipelines to use again and again.

This is where custom commands come in.

An example definition of a custom command:

```nu
def greet [name] {
  ['hello' $name]
}
```

::: tip
The value produced by the last line of a command becomes the command's returned value. In this case, a list containing the string `'hello'` and `$name` is returned. To prevent this, you can place `null` (or the [`ignore`](/commands/docs/ignore.md) command) at the end of the pipeline, like so: `['hello' $name] | null`. Also note that most file system commands, such as [`save`](/commands/docs/save.md) or [`cd`](/commands/docs/cd.md), always output `null`.
:::

In this definition, we define the `greet` command, which takes a single parameter `name`. Following this parameter is the block that represents what will happen when the custom command runs. When called, the custom command will set the value passed for `name` as the `$name` variable, which will be available to the block.

To run the above, we can call it like we would call built-in commands:

```nu
> greet "world"
```

As we do, we also get output just as we would with built-in commands:

```
───┬───────
 0 β”‚ hello
 1 β”‚ world
───┴───────
```

::: tip
If you want to generate a single string, you can use the string interpolation syntax to embed $name in it:

```nu
def greet [name] {
  $"hello ($name)"
}

greet nushell
```

returns `hello nushell`
:::

## Command names

In Nushell, a command name is a string of characters. Here are some examples of valid command names: `greet`, `get-size`, `mycommand123`, `my command`, and `😊`.

_Note: It's common practice in Nushell to separate the words of the command with `-` for better readability._ For example `get-size` instead of `getsize` or `get_size`.

## Sub-commands

You can also define subcommands to commands using a space. For example, if we wanted to add a new subcommand to [`str`](/commands/docs/str.md), we can create it by naming our subcommand to start with "str ". For example:

```nu
def "str mycommand" [] {
  "hello"
}
```

Now we can call our custom command as if it were a built-in subcommand of [`str`](/commands/docs/str.md):

```nu
> str mycommand
```

Of course, commands with spaces in their names are defined in the same way:

```nu
def "custom command" [] {
  "this is a custom command with a space in the name!"
}
```

## Parameter types

When defining custom commands, you can name and optionally set the type for each parameter. For example, you can write the above as:

```nu
def greet [name: string] {
  $"hello ($name)"
}
```

The types of parameters are optional. Nushell supports leaving them off and treating the parameter as `any` if so. If you annotated a type on a parameter, Nushell will check this type when you call the function.

For example, let's say you wanted to take in an `int` instead:

```nu
def greet [name: int] {
  $"hello ($name)"
}

greet world
```

If we try to run the above, Nushell will tell us that the types don't match:

```
error: Type Error
  β”Œβ”€ shell:6:7
  β”‚
5 β”‚ greet world
  β”‚       ^^^^^ Expected int
```

This can help you guide users of your definitions to call them with only the supported types.

The currently accepted types are (as of version 0.86.0):

- `any`
- `binary`
- `bool`
- `cell-path`
- `closure`
- `datetime`
- `directory`
- `duration`
- `error`
- `filesize`
- `float`
- `glob`
- `int`
- `list`
- `nothing`
- `number`
- `path`
- `range`
- `record`
- `string`
- `table`

## Parameters with a default value

To make a parameter optional and directly provide a default value for it you can provide a default value in the command definition.

```nu
def greet [name = "nushell"] {
  $"hello ($name)"
}
```

You can call this command either without the parameter or with a value to override the default value:

```nu
> greet
hello nushell
> greet world
hello world
```

You can also combine a default value with a [type requirement](#parameter-types):

```nu
def congratulate [age: int = 18] {
  $"Happy birthday! You are ($age) years old now!"
}
```

If you want to check if an optional parameter is present or not and not just rely on a default value use [optional positional parameters](#optional-positional-parameters) instead.

## Optional positional parameters

By default, positional parameters are required. If a positional parameter is not passed, we will encounter an error:

```nu
  Γ— Missing required positional argument.
   ╭─[entry #23:1:1]
 1 β”‚ greet
   Β·      β–²
   Β·      ╰── missing name
   ╰────
  help: Usage: greet <name>
```

We can instead mark a positional parameter as optional by putting a question mark (`?`) after its name. For example:

```nu
def greet [name?: string] {
  $"hello ($name)"
}

greet
```

Making a positional parameter optional does not change its name when accessed in the body. As the example above shows, it is still accessed with `$name`, despite the `?` suffix in the parameter list.

When an optional parameter is not passed, its value in the command body is equal to `null`. We can use this to act on the case where a parameter was not passed:

```nu
def greet [name?: string] {
  if ($name == null) {
    "hello, I don't know your name!"
  } else {
    $"hello ($name)"
  }
}

greet
```

If you just want to set a default value when the parameter is missing it is simpler to use a [default value](#parameters-with-a-default-value) instead.

If required and optional positional parameters are used together, then the required parameters must appear in the definition first.

## Flags

In addition to passing positional parameters, you can also pass named parameters by defining flags for your custom commands.

For example:

```nu
def greet [
  name: string
  --age: int
] {
  [$name $age]
}
```

In the `greet` definition above, we define the `name` positional parameter as well as an `age` flag. This allows the caller of `greet` to optionally pass the `age` parameter as well.

You can call the above using:

```nu
> greet world --age 10
```

Or:

```nu
> greet --age 10 world
```

Or even leave the flag off altogether:

```nu
> greet world
```

Flags can also be defined to have a shorthand version. This allows you to pass a simpler flag as well as a longhand, easier-to-read flag.

Let's extend the previous example to use a shorthand flag for the `age` value:

```nu
def greet [
  name: string
  --age (-a): int
] {
  [$name $age]
}
```

_Note:_ Flags are named by their longhand name, so the above example would need to use `$age` and not `$a`.

Now, we can call this updated definition using the shorthand flag:

```nu
> greet -a 10 hello
```

Flags can also be used as basic switches. This means that their presence or absence is taken as an argument for the definition. Extending the previous example:

```nu
def greet [
  name: string
  --age (-a): int
  --twice
] {
  if $twice {
    [$name $name $age $age]
  } else {
    [$name $age]
  }
}
```

And the definition can be either called as:

```nu
> greet -a 10 --twice hello
```

Or just without the switch flag:

```nu
> greet -a 10 hello
```

You can also assign it to true/false to enable/disable the flag too:

```nu
> greet -a 10 --switch=false
> greet -a 10 --switch=true
```

But note that this is not the behavior you want: `> greet -a 10 --switch false`, here the value `false` will pass as a positional argument.

To avoid confusion, it's not allowed to annotate a boolean type on a flag:

```nu
def greet [
    --twice: bool   # Not allowed
] { ... }
```

instead, you should define it as a basic switch: `def greet [--twice] { ... }`

Flags can contain dashes. They can be accessed by replacing the dash with an underscore:

```nu
def greet [
  name: string
  --age (-a): int
  --two-times
] {
  if $two_times {
    [$name $name $age $age]
  } else {
    [$name $age]
  }
}
```

## Rest parameters

There may be cases when you want to define a command which takes any number of positional arguments. We can do this with a rest parameter, using the following `...` syntax:

```nu
def greet [...name: string] {
  print "hello all:"
  for $n in $name {
    print $n
  }
}

greet earth mars jupiter venus
```

We could call the above definition of the `greet` command with any number of arguments, including none at all. All of the arguments are collected into `$name` as a list.

Rest parameters can be used together with positional parameters:

```nu
def greet [vip: string, ...name: string] {
  print $"hello to our VIP ($vip)"
  print "and hello to everybody else:"
  for $n in $name {
    print $n
  }
}

#     $vip          $name
#     ---- ------------------------
greet moon earth mars jupiter venus
```

To pass a list to a rest parameter, you can use the [spread operator](/book/operators#spread-operator) (`...`):

```nu
> let planets = [earth mars jupiter venus] # This is equivalent to the previous example
> greet moon ...$planets
```

## Documenting your command

In order to best help users of your custom commands, you can also document them with additional descriptions for the commands and parameters.

Taking our previous example:

```nu
def greet [
  name: string
  --age (-a): int
] {
  [$name $age]
}
```

Once defined, we can run `help greet` to get the help information for the command:

```nu
Usage:
  > greet <name> {flags}

Parameters:
  <name>

Flags:
  -h, --help: Display this help message
  -a, --age <integer>
```

You can see the parameter and flag that we defined, as well as the `-h` help flag that all commands get.

To improve this help, we can add descriptions to our definition that will show up in the help:

```nu
# A greeting command that can greet the caller
def greet [
  name: string      # The name of the person to greet
  --age (-a): int   # The age of the person
] {
  [$name $age]
}
```

The comments that we put on the definition and its parameters then appear as descriptions inside the [`help`](/commands/docs/help.md) of the command.

::: warning Note
A Nushell comment that continues on the same line for argument documentation purposes requires a space before the ` #` pound sign.
:::

Now, if we run `help greet`, we're given a more helpful help text:

```
A greeting command that can greet the caller

Usage:
  > greet <name> {flags}

Parameters:
  <name> The name of the person to greet

Flags:
  -h, --help: Display this help message
  -a, --age <integer>: The age of the person
```

## Pipeline Output

Custom commands stream their output just like built-in commands. For example, let's say we wanted to refactor this pipeline:

```nu
> ls | get name
```

Let's move [`ls`](/commands/docs/ls.md) into a command that we've written:

```nu
def my-ls [] { ls }
```

We can use the output from this command just as we would [`ls`](/commands/docs/ls.md).

```nu
> my-ls | get name
───┬───────────────────────
 0 β”‚ myscript.nu
 1 β”‚ myscript2.nu
 2 β”‚ welcome_to_nushell.md
───┴───────────────────────
```

This lets us easily build custom commands and process their output. Note, that we don't use return statements like other languages. Instead, we build pipelines that output streams of data that can be connected to other pipelines.

## Pipeline Input

Custom commands can also take input from the pipeline, just like other commands. This input is automatically passed to the block that the custom command uses.

Let's make our own command that doubles every value it receives as input:

```nu
def double [] {
  each { |it| 2 * $it }
}
```

Now, if we call the above command later in a pipeline, we can see what it does with the input:

```nu
> [1 2 3] | double
───┬─────
 0 β”‚ 2
 1 β”‚ 4
 2 β”‚ 6
───┴─────
```

We can also store the input for later use using the `$in` variable:

```nu
def nullify [...cols] {
  let start = $in
  $cols | reduce --fold $start { |col, df|
    $df | upsert $col null
  }
}
```

## Persisting

For information about how to persist custom commands so that they're visible when you start up Nushell, see the [configuration chapter](configuration.md) and add your startup script.