With zsh becoming the default shell in Terminal for MacOS, and a widely used shell in general thanks to Oh-My-Zsh, you may be wondering how to configure and use aliases with zsh shell.
What are Aliases?
Aliases in a shell are user-defined shortcuts or abbreviations for longer commands. They allow you to create custom commands that are easier to remember and type. Thankfully, it’s pretty easy to configure and use aliases with zsh shell in macOS.
How to Create an Alias in zsh
Zsh aliases are stored in the users zshrc file within the home directory, which is prefixed with a period to signify that it is hidden. Thus we must edit that file to configure aliases.
- Open the Terminal app on your Mac. You can do this by clicking on the Launchpad icon in your Dock and searching for “Terminal” or by pressing Command + Space and typing “Terminal” in Spotlight.
- To edit the .zshrc file in your home directory using nano, use the following command syntax:
nano ~/.zshrc
- Append to the bottom of this text file your desired alias(es) using the following format, with each new alias being on a separate line:
alias (aliasname)="command"
For example, to make an alias called "fullinstallers" that lists all available complete installers for MacOS using the softwareupdate command with the –list-full-installers flag, the syntax would be:
alias fullinstallers="softwareupdate --list-full-installers"
Another example, if you installed gcc with Homebrew on the Mac and you want to make it easier to run gcc rather than clang, you could use the following alias:
alias gcc="gcc-13"
Another example, is to use an alias if you find yourself frequently typing in a lengthy command to connect to a particular ssh server, like so:
alias remoteshell='ssh -p 123123 [email protected]'
- Place each alias onto a new line
- When finished modifying your .zshrc file with aliases, hit Control+O to save in nano, followed by Control+X to quit
- Back at the command line, use the source command to reload the shell profile configuration:
source ~/.zshrc
Your new alias(es) are now ready to use at the command line, just type the command you linked to the alias, and it will run. Using the examples above, that would be ‘remoteshell’, ‘gcc’, and ‘fullinstallers’.
If you use Oh-My-Zsh on the Mac, then you might want to run the ‘alias’ command first because you’ll find many prebundled aliases already in your .zshrc file that you might otherwise be setting up aliases to perform, like using color with ls for example.
Conclusion
Configuring aliases in Zsh on MacOS is a simple yet powerful way to enhance your command-line experience. By customising commands to match your workflow, you can save time and reduce the cognitive load associated with remembering complex commands. Take advantage of aliases to make your interaction with the terminal more efficient and enjoyable. Experiment with different aliases and tailor them to your needs.