Knowledge Garden

Search

Search IconIcon to open search

Bash Go to last used dir

Last updated Jan 30, 2023 Edit Source

cd -

or

cd "$SOLDPWD"

stack exchange answer

The other answers are definitely complete in the direct answer sense. cd - and cd $OLDPWD are definitely the main choices for this. However, I often find that getting into a workflow with pushd and popd works better.

Long story short, if you are moving into a directory with the ultimate intent of coming back to where you started, use pushd/popd.

# Extended example

The major difference is easily shown by an example.

1
2
$ cd dir1
$ pushd dir2

At this point, you have a directory stack that is dir2, dir1. Running pushd with no arguments will put you back in dir1 with the stack now as dir1, dir2. popd would do the same, but would leave you with an empty directory stack. This is not much different than how you would have been with the cd - workflow.

However, now you can now change directories multiple times and get back to dir1. For example,

1
2
3
$ cd dir1
$ pushd dir2
$ cd dir3

If you run popd at this point, you will go back to dir1.