Run shell script when navigating to directory with cd

6,075

Solution 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

Solution 2

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

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

Solution 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.

Share:
6,075

Related videos on Youtube

OlehZiniak
Author by

OlehZiniak

Updated on September 18, 2022

Comments

  • OlehZiniak
    OlehZiniak over 1 year

    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.