Global (ZSH) aliases are magic

If you pipe all of your commands into Emacs buffers, or build all of your software in an IDE, you might not have use for ZSH's delightful global aliases, but as someone who's often cutting and splicing text, these little tricks come in extremely handy.

Most shells offer aliases as a way of storing reusable snippets to ease invocation of command-line tools, which reduce the number of micro-languages one has to remember.

Consider this real-world example where I once had an http-serve alias to start a Python process to serve up a directory of files.

jamesconroyfinn.com on main [$?⇡] via ⬢ v20.3.1 via ❄️  impure (devenv-shell-env)
 python -m http
/nix/store/zdjdaym7n0k1g97a040xin1621cdfb7x-devenv-profile/bin/python: No module named http.__main__; 'http' is a package and cannot be directly executed

jamesconroyfinn.com on main [$?⇡] via ⬢ v20.3.1 via ❄️  impure (devenv-shell-env)
 python -m http.serve
/nix/store/zdjdaym7n0k1g97a040xin1621cdfb7x-devenv-profile/bin/python: No module named http.serve

jamesconroyfinn.com on main [$?⇡] via ⬢ v20.3.1 via ❄️  impure (devenv-shell-env)
 python -m http.server
Serving HTTP on :: port 8000 (http://[::]:8000/) ...
^C
Keyboard interrupt received, exiting.

Third time’s a charm! I’m sure any self-respecting Pythonista would know exactly which module Python 3 uses to provide this functionality, as well how to accomplish the same with Python 2 (for the curious, it was python -m SimpleHTTPServer).

Something ZSH offers that sets it apart is the ability to define what’s called a global alias. Global aliases can be used anywhere in a command and can feature pipe operators!

An example I use often is redirecting output to jq:

curl https://example.com/api.json J

Or redirecting all output to /dev/null:

cat /etc/passwd N

These don’t have to be in the tail position, and one can chain them as required.

If you’re using Home Manager to configure your ZSH environment, adding global aliases looks something like this:

programs.zsh.shellGlobalAliases = {
  C = "| pbc";
  F = "| fzf";
  G = "| rg";
  J = "| jq";
  L = "| less";
  N = "&>/dev/null";
};