Override a builtin command with an alias

I also tried cd(){ echo before; cd $1; echo after; } however it repetedly echos "before".

because it calls recursively the cd defined by you. To fix, use the builtin keyword like:

cd(){ pwd; builtin cd "$@"; pwd; }

Ps: anyway, IMHO isn't the best idea redefining the shell builtins.


Just to add to @jm666's answer:

To override a non-builtin with a function, use command. For example:

ls() { command ls -l; }

which is the equivalent of alias ls='ls -l'.

command works with builtins as well. So, your cd could also be written as:

cd() { echo before; command cd "$1"; echo after; }

To bypass a function or an alias and run the original command or builtin, you can put a \ at the beginning:

\ls # bypasses the function and executes /bin/ls directly

or use command itself:

command ls