You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: book/custom_commands.md
+56Lines changed: 56 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -678,6 +678,62 @@ vip-greet $vip ...$guests
678
678
# => And a special welcome to our VIP today, Tanisha!
679
679
```
680
680
681
+
### Rest Parameters with Wrapped External Commands
682
+
683
+
Custom commands defined with `def --wrapped` will collect any unknown flags and arguments into a
684
+
rest-parameter which can then be passed, via list-spreading, to an external command. This allows
685
+
a custom command to "wrap" and extend the external command while still accepting all of its original
686
+
parameters. For example, the external `eza` command displays a directory listing. By default, it displays
687
+
a grid arrangement:
688
+
689
+
```nu
690
+
eza commands
691
+
# => categories docs README.md
692
+
```
693
+
694
+
We can define a new command `ezal` which will always display a long-listing, adding icons:
695
+
696
+
```nu
697
+
def --wrapped ezal [...rest] {
698
+
eza -l ...$rest
699
+
}
700
+
```
701
+
702
+
:::note
703
+
You could also add `--icons`. We're omitting that in this example simply because those icons don't
704
+
display well in this guide.
705
+
:::
706
+
707
+
Notice that `--wrapped` forces any additional parameters into the `rest` parameter, so the command
708
+
can be called with any parameter that `eza` supports. Those additional parameters will be expanded via
709
+
the list-spreading operation `...$rest`.
710
+
711
+
```nu
712
+
ezal commands
713
+
# => drwxr-xr-x - ntd 7 Feb 11:41 categories
714
+
# => drwxr-xr-x - ntd 7 Feb 11:41 docs
715
+
# => .rw-r--r-- 936 ntd 14 Jun 2024 README.md
716
+
717
+
ezal -d commands
718
+
# => drwxr-xr-x - ntd 14 Jun 2024 commands
719
+
```
720
+
721
+
The custom command can check for certain parameters and change its behavior accordingly. For instance,
722
+
when using the `-G` option to force a grid, we can omit passing a `-l` to `eza`:
723
+
724
+
```nu
725
+
def --wrapped ezal [...rest] {
726
+
if '-G' in $rest {
727
+
eza ...$rest
728
+
} else {
729
+
eza -l --icons ...$rest
730
+
}
731
+
}
732
+
733
+
ezal -G commands
734
+
# => categories docs README.md
735
+
```
736
+
681
737
## Pipeline Input-Output Signature
682
738
683
739
By default, custom commands accept [`<any>` type](./types_of_data.md#any) as pipeline input and likewise can output `<any>` type. But custom commands can also be given explicit signatures to narrow the types allowed.
0 commit comments