Execute a bash function upon entering a directory

Aliases don't accept parameters. You should use a function. There's no need to execute it automatically every time a prompt is issued.

function cd () { builtin cd "$@" && myfunction; }

The builtin keyword allows you to redefine a Bash builtin without creating a recursion. Quoting the parameter makes it work in case there are spaces in directory names.

The Bash docs say:

For almost every purpose, shell functions are preferred over aliases.


I've written a ZSH script utilizing the callback function chpwd to source project specific ZSH configurations. I'm not sure if it works with Bash, but I think it'll be worth a try. If it doesn't find a script file in the directory you're cd'ing into, it'll check the parent directories until it finds a script to source (or until it reaches /). It also calls a function unmagic when cd'ing out of the directory, which allows you to clean up your environment when leaving a project.

http://github.com/jkramer/home/blob/master/.zsh/func/magic

Example for a "magic" script:

export BASE=$PWD # needed for another script of mine that allows you to cd into the projects base directory by pressing ^b

ctags -R --languages=Perl $PWD # update ctags file when entering the project directory

export PERL5LIB="$BASE/lib"

# function that starts the catalyst server
function srv {
  perl $BASE/script/${PROJECT_NAME}_server.pl
}

# clean up
function unmagic {
  unfunction src
  unset PERL5LIB
}

The easiest solution I can come up with is this

myfunction() {
  if [ "$PWD" != "$MYOLDPWD" ]; then
    MYOLDPWD="$PWD";
    # strut yer stuff here..
  fi
}

export PROMPT_COMMAND=myfunction

That ought to do it. It'll work with all commands, and will get triggered before the prompt is displayed.


There are a few other versions of this out there, including

  • smartcd, which I wrote, and has a ton of features including templating and temporary variable saving
  • ondir, which is smaller and much simpler

Both of these support both bash and zsh

Tags:

Function

Bash

Cd