Linux/Unix: Using pushd and popd to quickly change directories
đ Wiki page | đ Last updated: Oct 26, 2022Learning to use pushd
and popd
commands to work with the directory stack can be a very useful shell skill.
By default, the only directory on the stack is the current one. We can check that by using the dirs
command:
cd ~
dirs
The output should be just ~
.
Let's create a few directories to make things more interesting:
mkdir -p testdir/{d1,d2,d3}
Now, instead of changing the directory with cd
, let's use pushd
:
pushd testdir/d1
This has the same effect as cd testdir/d1
, but we have also pushed the previous directory to the stack, as indicated by the output from the pushd
command:
~/testdir/d1 ~
We can a bit nicer overview (with index numbers) by executing dirs -v
:
0 ~/testdir/d1
1 ~
Let's add other two directories to the stack:
pushd ../d2
pushd ../d3
Our stack now looks like this:
0 ~/testdir/d3
1 ~/testdir/d2
2 ~/testdir/d1
3 ~
If we want to quickly move to the previous directory (d2
), we can do that by removing the most recent directory from the stack with popd
:
~/testdir/d2 ~/testdir/d1 ~
Executing popd
again will move us into d1
and remove d2
from the stack:
~/testdir/d1 ~
We can also specify the index number of the entry to remove with popd +N
(starting from the left side), and popd -1N
(starting from the right side). For example popd +1
will remove ~
:
~/testdir/d1
This is a very simplistic scenario to demonstrate the basic idea, but I'm sure you can imagine scenarios where you're doing some work in multiple directories (and get distracted in the process), where this can be very useful.
This works out of the box in bash and zsh.
Rotating the stack
You can use pushd +N
or pushd -N
to rotate the stack. Positive numbers will rotate the stack so that the Nth directory (starting from the left side) is at the top. Negative numbers will do the opposite (starting from the right side).
Alternatives
If you only need to go one directory back, cd -
is a useful alternative.
For example, if we go from d1
to d2
, executing cd -
will move us back into d1
. If we execute cd -
again, we'll be back in d2
.
Ask me anything / Suggestions
If you find this site useful in any way, please consider supporting it.