- 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:
- Saves your current directory on the stack
- Changes to
/path/to/dir - 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:
- Removes the top directory from the stack
- 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?
| Command | Behavior |
|---|---|
cd | Go somewhere, forget previous place |
pushd | Go somewhere, remember previous place |
popd | Go 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
| Command | Meaning |
|---|---|
dirs | Show directory stack |
dirs -v | Numbered stack |
pushd +N | Rotate stack |
popd +N | Remove 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
pushdremembers where you were before changing directories;popdtakes you back—using a directory stack instead of forgetting history.