Linux: changing to previous directory

When you need to often check things in two different paths which are quite long, it’s really a pain to keep typing them again over and over. Luckily, you don’t have to.

There is an environment variable which contains the path you were at before changing directories:

# cd /var/log
# cd /usr/lib/gcc/
# echo $OLDPWD
/var/log

So basically all you need to type to get back to /var/log is:

cd "$OLDPWD"

Well it isn’t really short either so you’d probably want to create an alias or something… We’re again lucky since the cd command actually already has a solution for us:

# man builtins
...
cd [-L|-P] [dir]
... An argument of - is equivalent to $OLDPWD. ... if - is the first argument, and the directory change is successful, the absolute pathname of the new working directory is written to the standard output. ...
...

So basically:

cd -

is equivalent to:

cd "$OLDPWD" && pwd

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

An alternative to this is to use pushd and popd:

#cd /var/log
# pushd /usr/local/bin
/usr/local/bin /var/log
# pwd
/usr/local/bin
# popd
/var/log

The difference is that pushd builds a directory stack, so you can use it to push more than 1 directory and use popd to travel back in the stack. But it doesn’t allow you to go back and forth over and over.

Leave a Reply

Your email address will not be published. Required fields are marked *