Linux pushd and popd Command Tutorial for Beginners (3 Examples)
Command line navigation in Linux is primarily done using the cd command. However, there are several tips and tricks that may enhance your Linux command line navigation experience.
In this article, we will discuss two commands - pushd and popd - using some easy to understand examples. But before we do that, it's worth mentioning that all examples in this article have been tested on an Ubuntu 18.04 LTS system.
Linux pushd and popd commands
The pushd command stores a directory path in the directory stack while the popd command removes the top directory path from the same stack. In addition, both these commands make the directory being working on as your new working directory.
Following are some Q&A-styled examples that should give you a good idea on how these command line tools work.
Q1. How to use pushd?
Suppose you are working in a directory - say 'a' - on the command line. And you want to move into some other directory, but also want the system to remember your current directory 'a'.
Then here's where the pushd command can be of help. For example, see the following example:
himanshu@himanshu:~/Downloads/HTF-review$ pushd /home/himanshu/Desktop/
When this command is run, the current directory - /home/himanshu/Downloads/HTF-review/ - is saved on the directory stack and the directory /home/himanshu/Desktop becomes your new working directory.
The output produced by the pushd command is nothing but the current contents stored in the directory stack.
Q2. How to use popd?
Unlike pushd, you don't have to pass any input to popd. Here's how you use it:
When this command is run, the directory that's currently on top in the stack is picked and made your current working directory.
Here's an example:
So you can see, the directory /home/himanshu/Downloads/HTF-review became the current working directory of the user.
Q3. How to check directory stack?
While both pushd and popd commands show current stack entries in their output, there's a way you can see this info without running these commands as well.
It's by running the following command:
The following screenshot shows this command line tool in action:
Note that the current directory is always part of the directory stack.
So you can see, the pushd and popd commands have the potential to make user's life easy on the command line. We have covered these commands in detail here, just in case you want to learn more about them. Oh, and yes, do let us know in comments below how you use these commands to make life easier.