How to create and use aliases in Zsh

Repeated option-heavy commands are easy to mistype in an interactive Zsh terminal, especially when the same command is run many times during one session. A Zsh alias gives that command a short name for simple replacements such as a preferred ls format, while shell functions are better for shortcuts that need arguments, tests, or branching.

The alias builtin stores a name-to-command replacement in the current shell. A temporary alias starts working as soon as it is defined, and unalias removes it from that shell without changing any startup file.

Persistent aliases belong in ~/.zshrc because Zsh reads that file for interactive shells. Reload the file with source or open a new terminal, then confirm both the stored alias definition and the command output before relying on the shortcut.

Steps to create and use Zsh aliases:

  1. Define a temporary alias in the current terminal.
    $ alias ll='ls -lh'

    Do not put spaces around the equals sign. Quote the replacement command when it includes spaces or options.

  2. Confirm the alias definition.
    $ alias ll
    ll='ls -lh'

    Zsh prints alias definitions without the word alias in the output. The line still means ll expands to ls -lh.

  3. Run the alias against a directory.
    $ ll ~/projects/demo
    total 0
    -rw-r--r-- 1 operator operator 0 Jun  5 02:11 report.txt

    Zsh expands aliases in interactive shells. Use a function or the full command inside scripts instead of depending on user aliases.

  4. Remove the temporary alias when the shortcut is no longer needed.
    $ unalias ll
  5. Add the alias to ~/.zshrc.
    $ nano ~/.zshrc
    ~/.zshrc
    alias ll='ls -lh'

    Keep interactive aliases in ~/.zshrc. Use a function when the shortcut needs parameters, branching, or more than one command.

  6. Check ~/.zshrc for syntax errors.
    $ zsh -n ~/.zshrc

    No output from zsh -n means Zsh parsed the file without finding a syntax error.

  7. Reload ~/.zshrc in the current terminal.
    $ source ~/.zshrc
  8. Confirm that the persistent alias loaded.
    $ alias ll
    ll='ls -lh'
  9. Run the alias after reloading the startup file.
    $ ll ~/projects/demo
    total 0
    -rw-r--r-- 1 operator operator 0 Jun  5 02:11 report.txt