Bash – Is it possible to define directory-sensitive aliases in zsh (or any other shell)

aliasbashshellzsh

I want to use different aliases (or perhaps: the same alias differently) depending on the current working directory. For example, I might want to use l as a shorthand for ls with some extra options. I want to use two variants:

alias l="ls --sort=extension" # variant A
alias l="ls --quoting-style=literal" # variant B

Normally, I would like to use variant A. However, I want to use variant B when listing pictures – that is, when my working directory is ~/pictures. (This is merely a minimal example. My actual use case is more complicated.)

I am aware that I could simply write a function l() with a case differentiation on the output of $(pwd). However, I want a more robust solution which allows me to rename the specific directories without changing any alias (and that doesn’t clutter my .zshrc).

But is it possible to overwrite or add aliases, e.g. by setting up a local .zshrc within the relevant directory (like it is possible for vim and a local .vimrc)?

Furthermore, is it (also) possible in bash or any other shell?

Best Answer

If you are using oh my zsh, just activate the dotenv plugin:

plugins+=(dotenv)
ZSH_DOTENV_FILE=.any-name-you-like-for-the-per-directory-alias-file

Also consider direnv, which lets you export environment variables in a per-directory .envrc, and unset them when you move away (which dotenv cannot do). direnv is compatible with all the popular shells. However, it doesn't currently let you define aliases or functions.

You can still combine ilkkachu's approach with direnv, by creating a function (rather than an alias) that decides what to do based on one (or several) environment variables, which are in turn set by direnv.

Both approaches deal with the security aspect by having you manually whitelist directories in which the dot files will be sourced.

Related Question