Is it available to set script to run in a particular directory, when you cd into it?

For example if /foo is a directory with git project, is it possible, when cd /foo automatically run git status or some npm scripts?

Please don't link answer to strictly to git, imagine that could be any other command/script.


One of the ways you can do this is via alias command:

alias cdgit="cd /foo; git status"

Then you execute cdgit and you go to directory /foo and exec git status

| improve this answer | |

You can replace cd with a function which adds any processing you want:

cd() {
    builtin cd "$@"
    # Do whatever you want here
| improve this answer | |

I use something similar to Stephen Kitt's answer in my .bashrc:

function cd() {
  command cd "$@" || return

  if [[ -d .git ]]
    git status --short
    ls -al

You can create additional conditions to handle different things as needed.

NOTE: since we're clobbering the reference to the cd command, you have to use command cd, builtin cd, or \cd to prevent the function from calling itself and recursing forever. For this reason some might find it useful to rename this function.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.