Bash – Preventing use of `cd ..` in bash

aliasbash

I have set up an alias in my .bashrc as follows:

alias u='cd ..'

All is well in my world… until I type cd .. and cringe that I did not use my incredible new alias. In fact, with this particular thing, it's very ingrained. Hard to change my behavior – I need serious intervention.

So, I naturally tried to set up another alias to keep me from using cd ..:

alias 'cd ..'='echo "Use your alias!"'

But that apparently doesn't work. My thought is that this also might somehow conflict with the u alias, in some sort of infinite loop of aliasing.

Any ideas?

Best Answer

Anything more complicated that supplying a few extra arguments to a command is too much for an alias and requires a function instead. Use builtin cd to call the original.

cd () {
  if [ "$*" = ".." ]; then
    echo 1>&2 'Use your alias instead!'
    return 2
  else
    builtin cd "$@"
  fi
}

If you're running bash ≥4.0, I question the utility of this particular alias. Put shopt -s autocd in your ~/.bashrc, and just type .. or any other directory name to switch to it.

Related Question