0

I have the following function in my .bashrc file on WSL2:

cd() {
    builtin cd "$@" && ls
}

I've used this on Cygwin without issue for years, and it works just as well on WSL2, except for one problem: I can't seem to be able to use the built-in cd inside of a new alias in .bashrc.

If cd() was an alias instead of a function, I'd be able to escape it with:

alias new="\cd .. && echo 'This is a new alias'"

or

\cd ..

on the command line. But this override doesn't seem to work with the cd() function like it would with an alias.

Is it possible to override a function in Bash?

Hashim Aziz
  • 13,835

1 Answers1

3

Yes, by using builtin cd.

(The equivalent for external commands is command, e.g. ls() { command ls ...; }.)


Note that \ only works with aliases because their expansion happens before backslash handling and other parsing steps, so the shell actually tries to look up an alias literally named \cd (which does not exist).

So the trick doesn't work with functions because they act as completely normal commands and are resolved during a much later stage (at which point the backslash handling has already turned \foo into regular foo).

grawity
  • 501,077