pushd / popd / dirs
Overview
pushd, popd, and dirs maintain a directory stack in bash. pushd changes directory and pushes the previous location; popd returns; dirs lists the stack. Handy when hopping between build trees, config dirs, and logs without losing your place. For a single previous directory, cd - is enough.
Light operator page — stack gymnastics in large scripts belong in Scripting → Bash in this book.
Syntax
pushd [dir]
pushd +N | -N
popd
popd +N | -N
dirs [-clpv] [+N | -N]Common Options
dirs
| Option | Description |
|---|---|
-l |
Long paths (no ~ abbreviation) |
-p |
One entry per line |
-v |
Numbered list |
-c |
Clear stack (bash) |
pushd / popd
| Form | Description |
|---|---|
pushd dir |
Push current, cd to dir |
pushd |
Swap top two entries |
pushd +N / -N |
Rotate stack |
popd |
Pop top and cd there |
popd +N |
Delete Nth entry without rotating to it (see help) |
set -o / shopt can affect cd behavior (cdspell, autocd); stack commands still need valid paths.
Examples with Explanations
Jump and return
pwd
pushd /var/log
# ... inspect logs ...
popd
pwdNested hops
pushd /etc/nginx
pushd /etc/ssl/certs
dirs -v
popd
popdList the stack
dirs
dirs -v
dirs -l -pSwap two project roots
cd ~/src/app
pushd ~/src/infra
pushd # swap top twoNumbered rotation
dirs -v
pushd +2 # bring entry 2 to top and cdClear
dirs -cNotes
- Stack is per shell session — not shared across terminals.
- Failed
pushdto a bad path usually leaves the stack unchanged (bash) — still verifypwd. - Prefer absolute paths in muscle memory when trees are deep and symlinked.
CDPATHcan makepushd some-nameresolve in unexpected directories — know if you set it.- Fish/zsh have similar but not identical stack commands.
Additional Resources
help pushd,help popd,help dirsman bash(DIRECTORY STACK)