Published on

pushd and popd in Shell

In shell (bash / zsh), pushd and popd are built-in commands used to navigate directories using a stack, not just a single “current directory”.

Think of it as bookmarking directories and jumping back and forth easily.


1. The directory stack (mental model)

The shell maintains a stack of directories:

[top]  ← current directory
        previous directories
[bottom]

You can view it with:

dirs

2. pushd — go to a directory and remember where you came from

Basic usage

pushd /path/to/dir

What it does:

  1. Saves your current directory on the stack
  2. Changes to /path/to/dir
  3. Makes the new directory the top of the stack

Example

pwd
# /home/user

pushd /var/log
# /var/log /home/user

pwd
# /var/log

Check stack:

dirs
# /var/log /home/user

pushd without arguments

pushd

This swaps the top two directories in the stack — very useful for toggling between two locations.


3. popd — go back to the previous directory

Basic usage

popd

What it does:

  1. Removes the top directory from the stack
  2. Changes to the new top directory

Example

Continuing from above:

popd
# /home/user

pwd
# /home/user

Stack now:

dirs
# /home/user

4. Why not just use cd?

CommandBehavior
cdGo somewhere, forget previous place
pushdGo somewhere, remember previous place
popdGo back automatically

pushd/popd shine when:

  • You jump between multiple directories
  • You’re writing scripts
  • You want to return safely even after many cds

5. Practical examples

A. Temporary directory jump

pushd /tmp
# do something
popd

Equivalent to “go there, then come back”.


B. Multiple locations

pushd /etc
pushd /var/log
pushd /usr/local/bin

Now:

dirs
# /usr/local/bin /var/log /etc /home/user

Jump back step-by-step:

popd   # /var/log
popd   # /etc
popd   # /home/user

C. Access stack entries directly

dirs -v

Output:

0  /usr/local/bin
1  /var/log
2  /etc
3  /home/user

Jump to an entry:

pushd +2   # go to /etc

6. Common options

CommandMeaning
dirsShow directory stack
dirs -vNumbered stack
pushd +NRotate stack
popd +NRemove entry N

7. In scripts (best practice)

pushd /some/dir > /dev/null
# do work
popd > /dev/null

Suppresses noisy output while keeping safety.


8. One-sentence summary

pushd remembers where you were before changing directories; popd takes you back—using a directory stack instead of forgetting history.