Bash Aliases – Is Aliasing cd to pushd a Good Idea?

aliasbashshellshell-script

Is it a good idea to use the following alias:

cd() {
    pushd $1;
}

in bash?

I think this would be very useful, since I can then use a series of popds instead of just a cd - once.

Is there any case where this might be a problem?

Best Answer

Personally, I have these in my bashrc and use them all the time:

pushd()
{
  if [ $# -eq 0 ]; then
    DIR="${HOME}"
  else
    DIR="$1"
  fi

  builtin pushd "${DIR}" > /dev/null
  echo -n "DIRSTACK: "
  dirs
}

pushd_builtin()
{
  builtin pushd > /dev/null
  echo -n "DIRSTACK: "
  dirs
}

popd()
{
  builtin popd > /dev/null
  echo -n "DIRSTACK: "
  dirs
}

alias cd='pushd'
alias back='popd'
alias flip='pushd_builtin'

You can then navigate around on the command-line a bit like a browser. cd changes the directory. back goes to the previous directory that you cded from. And flip will move between the current and previous directories without popping them from the directory stack. Overall, it works great.

The only real problem that I'm aware of is the fact that it's then a set of commands that I'm completely used to but don't exist on anyone else's machine. So, if I have to use someone else's machine, it can be a bit frustrating. If you're used to just using pushd and popd directly, you don't have that problem. And while if you just alias cd put not popd, you won't have the issue of back not existing, you'll still have the problem that cd doesn't do quite what you expect on other machines.

I would note, however, that your particular implementation of cd doesn't quite work like cd in that the normal cd by itself will go to your home directory, but yours doesn't. The version that I have here doesn't have that problem. Mine also appends DIRSTACK onto the front of the dirs print out, but that's more a matter of personal taste more than anything.

So, as I said, I use these aliases all the time and have no problem with them. It's just that it can be a bit frustrating to have to use another machine and then find them not there (which shouldn't be surprising, but they're one of those things that you use so often that you don't think about them, so having them not work like you're used to can still be surprising).

Related Question