zsh tips and tricks

Image of Author
August 11, 2023 (last updated September 1, 2023)

aliases

You can set aliases as follows:

alias g='git'

You can save these in your ~/.zshrc, but also, you can set these per terminal session. For example, if you were going to explore a executable that normally has a long name, you can temporarily shorten it for a single terminal session, and it will go away once you close the session.

alias o='openssl'

autoload and fpath

This can get complicated, you can learn more via man zshbuiltins section on autoload and via the man zshmisc section on "Autoloading Functions".

autoload and fpath are used in conjunction to create lazily executed functions in the terminal. When you autoload a function, you essentially set it to undefined. When you execute that function, it checks fpath directories for that function and loads it and executes it, if found.

For example

cd ~
mkdir alpha
touch alpha/beta
echo "echo gamma" > alpha/beta
# in .zshrc
fpath+=~/alpha
autload beta

Both fpath and autoload are necessary in order for this to work. (There are a few ways to construct functions, according to the man zshmisc section "Autoloading Functions", but from what I can tell, they all require autoloading and fpath.)

Then, in a new terminal,

beta
# => gamma

Importantly, calling autoload on a function does not execute the function. That's why you commonly see the following in .zshrc files:

autoload -Uz compinit
compinit

You first tell zsh to "prepare" the function (in the example, it's compinit, which initialises zsh completions). This makes the function available for both loading and executing. You then call the function itself (in the example, compinit). You will see this pattern for any custom functions you want to call immediately within the .zshrc file.

The -Uz flags are not crucial to understanding the flow, but for completeness, -U suppresses alias expansion and -z ensures zsh-style autoload behavior is used.

completions (via compinit)

Many CLI tools include completions for various popular shells, zsh likely being one of those shells. In general, the way they are composed is a particular command within the tool will output the shell code required to enable completions. If your package manager does not handle this for you (brew often does, by the way, see the "caveats" section of brew info [tool]) then you might have to include them yourself. Your job will be to ensure you have a folder in the #fpath and then to add the functions to that folder. It will likely be best to name the file with a leading underscore, as that is the zsh completion file convention. Also, you will likely see a #compdef ... in the first line of the completion file, which is used internal to the completion system.

It gets complicated, but you can read more via man zshcompsys.