Reputation: 862
(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.
Upvotes: 2
Views: 462
Reputation: 862
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.)
Upvotes: 2
Reputation: 45576
The alias doesn't work because aliases don't support arguments, so you cannot chain commands that require parameters. Because of this cd "$@"
doesn't make sense in the context of an alias and whatever argument you supply to an alias just gets appended:
$ alias foo='echo "[$@]" && echo'
$ foo bar
[]
bar
Obviously, that's not what you want and exactly why you need to resort to a function.
Upvotes: 0