(Since I couldn't find an explicit answer to this anywhere and I find it useful, I thought I would add it to SO. Better alternatives welcome.)
In Bash, how do you alias cd
to echo the new working directory after a change? Like this:
$ pwd
/some/directory
$ cd newness
/some/directory/newness
$
Something simple like alias cd='cd "$@" && pwd'
doesn't work. For some reason, Bash responds as though you used cd -
and returns to $OLDPWD
and you get caught in a loop. I don't understand this behavior.
Apparently, you need to do this through a function:
function mycd() {
cd "$@" && pwd
}
alias cd=mycd
However, if you use cd -
you wind up printing the directory twice, so this is more robust:
function mycd() {
if [ "$1" == "-" ]; then
cd "$@"
else
cd "$@" && pwd
fi
}
alias cd=mycd
I may be missing some edge cases, like cd -P -
and cd -L -
, though I don't know if those even make sense.
(See Adrian Frühwirth's answer below for the reason why a simple alias doesn't work and why I feel dumb now.)