0

This question already has an answer here:

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.

marked as duplicate by Gilles bash May 24 '17 at 22:48

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

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

3

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

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

  if [[ -d .git ]]
  then
    git status --short
  else
    ls -al
  fi
}

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.

2

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

cd() {
    builtin cd "$@"
    # Do whatever you want here
}

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