How to Use Linux Commands pushd and popd
The commands pushd
and popd
operate with the command line directory stack in computing.
Linux and other Unix-like operating systems, the commands pushd
and popd
allow you to interact with directory stacks and modify the current working directory. Even though pushd
and popd
are mighty and helpful commands, they are not much appreciated and utilized.
Use the pushd
Command in Linux
There are two entries in the stack after the first pushd
command: your left directory and the one you have.
The pushd
command has the following:
$ pushd ~/Desktop
Output:
~/Desktop ~
The directory of the terminal will be changed to Desktop
. i.e., ~/Desktop$
~/Desktop$ pushd ~/Music
Output:
~/Music ~/Desktop ~
Now, it’s changed to Music
.
$ pushd ~
Output:
~ ~/Music ~/Desktop ~
We returned to our home directory with the last pushd
command.
Therefore, the tilde~
, which symbolizes our home directory, is the first and last entry on the stack. It indicates that despite a directory already present in the stack, we will add it again for other pushd
commands.
Use the popd
Command in Linux
The popd
command is being used to remove directories from the stack. When we look at the directory stack, we see that /home/user
is in position 1
.
We type the following to pass the number to popd
to remove it from the stack:
$ dirs -v -l
Output:
0 /home/user
1 /home/user/Music
2 /home/user/Desktop
3 /home/user
$ popd +1
Output:
~ ~/Desktop ~
The /home/user
directory was eliminated, and all directories below it in the stack were pushed up one position.
$ popd
Output:
~/Desktop
We’ll use popd
to remove the top-most directory from the stack and replace it with the second-most directory.
This is now the directory you recently moved out of, so you’ve been redirected back to it.
Overstamping the Stack
It’s simple to revert to old habits and shift directories with cd
.
You’ll stamp over the first directory in the stack if you do so. It is unavoidable because the first slot is designated for the current working directory, and none move.
To do so, type the following into the terminal:
$ dirs -v -l
Output:
0 /home/user/Desktop
$ cd ~/Music
~/Music$ dirs -v -l
Output:
0 /home/user/Music
You’ll have a super-fast way to jump between folders once you get familiar with the pushd
and popd
commands and potentially utilize them to construct a few aliases.