Tags

, , ,

First the “bad” way of doing it:
I would create an alias bk to go to the previous directory, which looks like the following:

In BASH:
alias bk='cd "$OLDPWD"'

In CSH/TCSH:
alias cd 'set old=$cwd;if ("\!:0-$" == cd) cd;if ("\!:0-$" != cd) cd \!$'
alias bk 'set backdir=$cwd;chdir $old;set old=$backdir;unset backdir'

(In my C-Shell, somehow the OLDPWD is undefined; that’s why I had to find a way around. Does anyone know how to set it?)

But there is a far better and more elegant way of doing it (which I just picked up from Commandline-fu:
$ cd -
Yeah, just the hyphen will take you to the previous directory! This works if the $OLDPWD variable is set (which is not set when you log in).

How about changing the aliases now?
alias bk='if [ -n "${OLDPWD+x}" ]; then cd -; else cd ~; fi'
in BASH, and
alias bk 'cd -'
in CSH or TCSH. Now they look a lot smarter!

Advertisements