# How to change to the previous directory instead of going up

shellunix

I currently spend a lot of my working hours moving back and forth between two paths which are very far down the tree and divert from each other at root. It strikes me that my life would be a lot easier if there was an argument for cd that takes the user to the last directory they were in.

That is, if I'm in:

/etc/foo/bar/baz/moo


and then type:

cd /var/lib/fubarred_app/blargh/logs


I would like to be able to go back to the first directory without having to type the whole path again.

The memory key does not cut it since I use enough commands in each place that it's just as difficult to go back and find the path I want as it is to type it myself.

Is there a short command that would just let me go to the previous directory?

The command

cd -


will perform the swap you need on most of the mainstream shells, the older longer variant is

cd "$OLDPWD"  which will use the environment variable that contains the previous working directory. The POSIX man page for cd mentions: DESCRIPTION If, during the execution of the above steps, the PWD environment variable is changed, the OLDPWD environment variable shall also be changed to the value of the old working directory (that is the current working directory immediately prior to the call to cd). OPERANDS - When a hyphen is used as the operand, this shall be equivalent to the command: cd "$OLDPWD" && pwd


which changes to the previous working directory and then writes its name.