I was searching for a way to do this for quite a while, and today I came up with a solution that is a synthesis of some of the other answers, but with a secret ingredient that spikes the sauce; direnv
.
The problem with having .aliases
that is read every time, as proposed by @teknopaul, is as mentioned, that you accumulate definitions and they never unload. direnv
solves this issue by loading and unloading environment variables on a per-directory basis. Still, this just handles environment variables, but we can use this together with functions!
So here is my alias for npm
(which, of course, is not an alias, but a function):
function npm(){ if [[ -z "$NPMBIN" ]]; then $(which npm) $@; else $NPMBIN $@; fi; }
You can also rewrite the above to a true alias
, by executing the logic in a sub-shell, but then you need to mind your escaped quotes!
alias npm='bash -c "if [[ -z \"$NPMBIN\" ]]; then $(which npm) $@; else \"$NPMBIN\" $@; fi;"'