Execute a bash function upon entering a directory Execute a bash function upon entering a directory bash bash

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.


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