zsh – How to Stack Shell Aliases

aliaszsh

In my .profile (sourced in sh emulation mode from my .zshrc) I have the following snippet:

if [ -f /usr/bin/pacmatic ]; then
    alias pacman=pacmatic
fi

# Colorized Pacman output
alias pacman="pacman --color auto"

However, the second alias always overrides the first:

% type pacman
pacman is an alias for pacman --color auto

How can I make it so that the second alias assignment "inherits" the first assignment, so that if /usr/bin/pacmatic exists, the alias becomes pacmatic --color auto?

I'm not averse to using functions instead of aliases, but I'd prefer it if the logic wasn't performed every time pacman is invoked (I want pacmatic checked for once, at shell startup, not every time pacman is run). I'd also prefer an sh-portable script, but if this isn't possible, you can use full zsh syntax.

(Yes, I'm aware that this could easily be solved by appending --color auto to the pacmatic alias. But I want to do it the Right Way™.)

I've tried Googling and looking through the manpages, but to no avail.

Best Answer

A shell alias behaves pretty similarly to a #define, i.e. redefining a shell alias would override the previous one.

I'm not sure what would be the Right WayTM, but one approach would be making use a shell function that accepts parameters and using that to create an alias. Your code snippet could be rewritten as:

if [ -f /usr/bin/pacmatic ]; then
    pacman() { pacmatic "$@"; }
fi

# Colorized Pacman output
alias pacman="pacman --color auto"

 


Moreover, even if you were using different aliases and were trying to use one for defining the other, it would not work as aliases are not expanded in non-interactive mode by default. You need to enable it by setting expand_aliases:

shopt -s expand_aliases

Quoting from the manual:

   Aliases are not expanded when the shell is not interactive, unless  the
   expand_aliases  shell option is set using shopt (see the description of
   shopt under SHELL BUILTIN COMMANDS below).
Related Question