How to set an alias on a per-directory basis?

It is not completely sure what you are asking, but an alias just expands to what is in the alias. If you have two aliases, you can append the different commands, even aliases.

alias "foo=cd /path/to/foo; go"
alias "foo2=cd /path/to/foo2; go"

In any other situation, you could specify a function in your .bashrc

function go ()
{
    if [ "$PWD" == "/path/to/foo" ]; then
       cmd1
    elif [ "$PWD" == "/path/to/go" ]; then
       cmd2
    fi;
}

In case you have more choices, you could better use a case structure.


I get the feeling you are very "directory oriented", and, in that case, this might suite your mentality better.

(But to be honest, I think this is a bad idea altogether, you'd like commands to be global.)

In .bashrc, put alias go="./.cmd" (then source ~/.bashrc).

Then, in each such directory, put a script called .cmd, then chmod +x .cmd, then just go do your thing.


If you add the following function to your .bashrc

function cd () { 
  builtin cd "$@" && [[ -f .aliases ]] && . .aliases
  return 0
}

Every time you cd to a directory with an .aliases file it will get sourced.

Careful with security if others can create files on your machine.

With this trick aliases never get removed but you can write as much code as you like in the function.

ondir uses this trick and has a ton of bells and whistles.

http://swapoff.org/ondir.html#download