Execute a bash function upon entering a directory

Paul Biggar picture Paul Biggar · Jul 29, 2010 · Viewed 8.7k times · Source

I'd like to execute a particular bash function when I enter a new directory. Somethink like:

alias cd="cd $@ && myfunction"

$@ doesn't work there, and adding a backslash doesn't help. I'm also a little worried about messing with cd, and it would be nice if this worked for other commands which changed directory, like pushd and popd.

Any better aliases/commands?

Answer

Dennis Williamson picture Dennis Williamson · Jul 29, 2010

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.