Working on the Linux command line means switching between a lot of directories. Suppose you are in Directory ‘A’ and then move to Directory ‘B’. When you want to come back to Directory ‘A’, typing the complete directory path for ‘A’ can be cumbersome sometimes. Here’s a simple trick for this. You can use ‘cd-‘ to go back to the last directory you were in.
Lets see how this works by using an example:
Your current working directory is:
Your new working directory is:
$ cd /usr/local/bin/
The following command takes you back to your old working directory:
$ cd –
So you can see that it’s easy to switch between two directories using ‘cd-‘.
But, ‘cd –‘ resolves only part of the problem. It can only switch you back to the last working directory. What if you switch between multiple directories and then want to return to the first or some other desired directory? I mean, suppose you begin in Directory ‘A’, then want to return to Directory ‘A’.
For this, you can use the combination of ‘pushd’ and ‘popd’.
Here is an example:
$ pushd /home/himanshu
$ cd /usr
$ cd /tmp
As you can see, you first pass the desired directory(to which you want to come back to eventually) as the argument to ‘pushd’. Then through ‘popd’ you can actually trigger a directory switch to that directory from anywhere on the command prompt.