Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 30 additions & 31 deletions book/aliases.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,42 +63,13 @@ displaying all listed files and folders in a grid.
## Replacing Existing Commands Using Aliases

::: warning Caution!
When replacing commands it is best to "back up" the command first and avoid recursion error.
When replacing commands, use the percent sigil `%` to call the builtin command and avoid recursion error.
:::

How to back up a command like `ls`:

```nu
alias core-ls = ls # This will create a new alias core-ls for ls
```

Now you can use `core-ls` as `ls` in your nu-programming. You will see further down how to use `core-ls`.

The reason you need to use alias is because, unlike `def`, aliases are position-dependent. So, you need to "back up" the old command first with an alias, before re-defining it.
If you do not backup the command and you replace the command using `def` you get a recursion error.

```nu
def ls [] { ls }; ls # Do *NOT* do this! This will throw a recursion error

#output:
#Error: nu::shell::recursion_limit_reached
#
# × Recursion limit (50) reached
# ╭─[C:\Users\zolodev\AppData\Roaming\nushell\config.nu:807:1]
# 807 │
# 808 │ def ls [] { ls }; ls
# · ───┬──
# · ╰── This called itself too many times
# ╰────
```

The recommended way to replace an existing command is to shadow the command.
Here is an example shadowing the `ls` command.

```nu
# alias the built-in ls command to ls-builtins
alias ls-builtin = ls

# List the filenames, sizes, and modification times of items in a directory.
def ls [
--all (-a), # Show hidden files
Expand All @@ -112,7 +83,7 @@ def ls [
...pattern: glob, # The glob pattern to use.
]: [ nothing -> table ] {
let pattern = if ($pattern | is-empty) { [ '.' ] } else { $pattern }
(ls-builtin
(%ls
--all=$all
--long=$long
--short-names=$short_names
Expand All @@ -125,3 +96,31 @@ def ls [
) | sort-by type name -i
}
```

Forgetting the `%` will lead to an error:

```nu
def ls [] { ls }; ls # Do *NOT* do this! This will throw a recursion error

#output:
#Error: nu::shell::recursion_limit_reached
#
# × Recursion limit (50) reached
# ╭─[C:\Users\zolodev\AppData\Roaming\nushell\config.nu:807:1]
# 807 │
# 808 │ def ls [] { ls }; ls
# · ───┬──
# · ╰── This called itself too many times
# ╰────
```

If you want to wrap an already defined (non-built-in) function, you can use alias to "back up" the original

```nu
alias ls-prev = ls
def ls [] {
ls-prev | table --icons
}
```

You can use alias is because, unlike `def`, aliases are position-dependent. So, you can "back up" the old command first with an alias, before re-defining it.