Directory Stack with pushd, popd, and dirs
cd moves you to a new folder and forgets where you were, apart from the single previous folder that cd - returns to. When you work in several places at once, such as a project folder, a log folder and a configuration folder, you need a longer memory. Bash provides one: the directory stack, a list of folders managed with three built-in commands:
pushd DIRchanges toDIRand adds it to the top of the stack, keeping the old folder below it;popdremoves the top entry and changes to the folder that is now on top;dirsshows the stack.
A stack is a list where items are added and removed at the same end, the "top", like a stack of plates. The last folder you pushed is the first one you pop, which matches how work usually goes: you step into a folder, finish there, and step back out.
How the Stack Works
The top of the stack (entry 0) is always the current folder. The other entries are folders you can return to. When a shell starts, the stack holds just one entry, the current folder.
/home/claude$ cd ~
~$ dirs
~
~$ pushd projects/site
~/projects/site ~
~/projects/site$ pushd /var/log
/var/log ~/projects/site ~
/var/log$ pushd /etc
/etc /var/log ~/projects/site ~
(The prompt shows the current folder with \w, lesson 145.) After every pushd, Bash prints the whole stack on one line, top first. Each pushd put the new folder in front and moved the others one place to the right. Your home folder is shown as ~.
dirs -v lists the stack vertically with the entry numbers:
/etc$ dirs -v
0 /etc
1 /var/log
2 ~/projects/site
3 ~
The stack is also available as the array variable DIRSTACK, with full paths:
/etc$ echo "${DIRSTACK[@]}"
/etc /var/log /home/ana/projects/site /home/ana
pushd: Adding and Switching
| Form | Effect |
|---|---|
pushd DIR | go to DIR, put it on top of the stack |
pushd | swap the two top entries (go to the previous folder) |
pushd +N | rotate the stack so that entry N (counted from the top) comes to the top |
pushd -N | the same, counting from the bottom (-0 is the last entry) |
pushd -n DIR | add DIR as entry 1 without changing folder |
pushd without an argument swaps the two top entries, so calling it repeatedly toggles between two folders:
/etc$ pushd
/var/log /etc ~/projects/site ~
/var/log$ pushd
/etc /var/log ~/projects/site ~
pushd +N rotates the stack: entry N moves to the top, and the entries above it move to the bottom in the same order, so no folder is lost:
/etc$ pushd +2
~/projects/site ~ /etc /var/log
~/projects/site$ dirs -v
0 ~/projects/site
1 ~
2 /etc
3 /var/log
Entry 2 was ~/projects/site; it is now on top, and /etc and /var/log moved to the end. With dirs -v and pushd +N, the stack works like a numbered list of bookmarks.
popd: Removing Entries
| Form | Effect |
|---|---|
popd | remove the top entry and go to the new top |
popd +N | remove entry N (counted from the top) without changing folder, unless N is 0 |
popd -N | remove entry N counted from the bottom |
popd -n | remove entry 1 without changing folder |
Continuing the session:
~/projects/site$ popd
~ /etc /var/log
~$ popd +1
~ /var/log
~$ dirs -v
0 ~
1 /var/log
The first popd removed ~/projects/site and moved to ~, the new top. popd +1 removed /etc from the middle of the stack and stayed in ~.
pushd -n adds a folder without going there, and popping eventually empties the stack:
~$ pushd -n /tmp
~ /tmp /var/log
~$ popd
/tmp /var/log
/tmp$ popd
/var/log
/var/log$ popd
bash: popd: directory stack empty
/var/log$ echo "status $?"
status 1
When only the current folder is left, there is nothing to return to, so popd fails with status 1. pushd also fails with status 1 if the folder does not exist, and the stack is not changed:
/var/log$ pushd /nope; echo "status $?"
bash: pushd: /nope: No such file or directory
status 1
dirs: Showing and Clearing the Stack
| Form | Effect |
|---|---|
dirs | the stack on one line, home folder as ~ |
dirs -v | one entry per line, with numbers |
dirs -p | one entry per line, without numbers |
dirs -l | full paths instead of ~ |
dirs +N | only entry N |
dirs -c | clear the stack (only the current folder stays) |
/tmp$ dirs
/tmp ~/projects/site ~
/tmp$ dirs -l
/tmp /home/ana/projects/site /home/ana
/tmp$ dirs +1
~/projects/site
Tilde Shortcuts for Stack Entries
Tilde expansion (lesson 51) can refer to stack entries: ~N is entry N, ~+ is the current folder and ~- is the previous folder (OLDPWD). This makes the stack useful for copying files between folders:
~$ dirs -v
0 ~
1 /tmp
2 /var/log
~$ echo ~1 ~2
/tmp /var/log
A command such as cp ~2/app.log ~1/ would copy a file from the third entry to the second, without typing either path.
How cd Interacts with the Stack
cd changes the current folder, and because entry 0 is always the current folder, cd replaces the top entry instead of adding one:
~$ pushd projects/site >/dev/null
~/projects/site$ pushd /var/log >/dev/null
/var/log$ dirs
/var/log ~/projects/site ~
/var/log$ cd /tmp
/tmp$ dirs
/tmp ~/projects/site ~
/var/log was replaced by /tmp, and the rest of the stack was untouched. cd and pushd can be mixed freely, but only pushd remembers the folder you leave.
cd - is the simpler tool when you only need to alternate between two folders. It uses the variable OLDPWD and prints the folder it changes to:
/tmp$ cd ~/projects/api
~/projects/api$ cd -
/tmp
/tmp$ cd -
/home/ana/projects/api
| Need | Tool |
|---|---|
| go back to the folder you just left | cd - |
| toggle between two folders | cd - or pushd |
| remember several folders and return in reverse order | pushd and popd |
| jump among a fixed set of folders by number | dirs -v and pushd +N |
Using pushd and popd in Scripts
Scripts often need to work in another folder and then return. pushd and popd do this, with two details to handle:
- both print the stack on standard output, which would mix with the script's real output, so redirect them to
/dev/null; pushdfails when the folder is missing, and the script must not continue in the wrong folder, so check its status.
cd /home/ana
echo "--- pushd prints the stack"
pushd projects/site
popd
echo "--- quiet"
pushd projects/api > /dev/null || exit
echo "working in $PWD"
popd > /dev/null
echo "back in $PWD"
echo "--- failure"
pushd /nope > /dev/null || echo "pushd failed with status $?"
--- pushd prints the stack
~/projects/site ~
~
--- quiet
working in /home/ana/projects/api
back in /home/ana
--- failure
/home/ana/t150.sh: line 11: pushd: /nope: No such file or directory
pushd failed with status 1
The error message itself goes to standard error, so it is still visible when standard output is redirected.
A subshell (lesson 93) is the alternative: ( cd dir && command ) changes folder only inside the subshell, and the script's own folder never changes, so there is nothing to undo:
( cd projects/site && echo "subshell in $PWD" )
echo "after subshell: $PWD"
subshell in /home/ana/projects/site
after subshell: /home/ana
The subshell is safer when the work is short, because a forgotten popd cannot happen. pushd/popd are the better fit when the commands in the other folder must change variables of the script, which a subshell cannot do, or when the steps between are long. The directory stack belongs to one shell: child processes, including scripts started from your terminal, begin with their own one-entry stack.
A Complete Example: Running a Command in Every Project
in-each.sh runs one command inside every subfolder of a folder, such as git status in every repository under ~/projects. It uses the directory stack to enter each folder and return, keeps going when the command fails in one folder, and reports the failures at the end.
#!/usr/bin/env bash
# in-each.sh: run one command inside every subfolder of a folder
# usage: in-each.sh ROOT COMMAND [ARG...]
# Prints a header per folder, keeps going after failures, and exits
# with status 1 if the command failed in any folder.
set -uo pipefail # no -e: a failing command must not stop the loop
shopt -s nullglob # a folder without subfolders gives an empty list
if (( $# < 2 )); then
echo "usage: ${0##*/} ROOT COMMAND [ARG...]" >&2
exit 2
fi
root=$1
shift
pushd -- "$root" > /dev/null || exit 1 # stack: ROOT, starting folder
failed=()
count=0
for dir in */; do
dir=${dir%/}
count=$((count + 1))
echo "== $dir"
if ! pushd -- "$dir" > /dev/null; then # stack: dir, ROOT, starting folder
failed+=("$dir (cannot enter)")
continue
fi
"$@"
status=$?
popd > /dev/null # back to ROOT
if (( status != 0 )); then
echo "-- failed with status $status"
failed+=("$dir (status $status)")
fi
done
popd > /dev/null # back to the starting folder
if (( count == 0 )); then
echo "No subfolders in $root"
exit 0
fi
echo
if (( ${#failed[@]} > 0 )); then
printf 'Failed in %d folder(s):\n' "${#failed[@]}"
printf ' %s\n' "${failed[@]}"
exit 1
fi
echo "Done: the command succeeded in all $count folders."
How It Works
- No
set -e: the command is expected to fail in some folders, and the script must record the failure and continue (lesson 119).-uandpipefailstay on. shopt -s nullglob(lesson 149) makes*/produce an empty list when the root has no subfolders, so the loop does not try to enter a folder literally named*.*/matches only folders, each with a trailing slash, which${dir%/}removes for the messages. Hidden folders are skipped.- The stack grows and shrinks in a fixed rhythm: the first
pushdputs the root on top of the starting folder; inside the loop,pushdadds the project folder andpopdreturns to the root; the finalpopdreturns to the starting folder. The comments show the stack at each step. "$@"runs the command with all its arguments exactly as given, so commands with spaces or quotes in their arguments work (lesson 89). Its status is saved instatusimmediately, beforepopdchanges$?.--afterpushdprotects against folder names that begin with a dash.- The
failedarray (lesson 99) collects one line per problem, and the final status is 1 when it is not empty, so the script can be used in other scripts or in CI.
Running the Complete Example
~/projects contains three Git repositories, api, site and old site (a name with a space), and a plain folder notes. site has an uncommitted change.
./in-each.sh projects git status --short; echo "status $?"; echo "pwd: $PWD"
== api
== notes
fatal: not a git repository (or any of the parent directories): .git
-- failed with status 128
== old site
== site
M README.md
Failed in 1 folder(s):
notes (status 128)
status 1
pwd: /home/ana
git status --short printed nothing for the clean repositories and M README.md for the modified one. In notes, Git failed with status 128; the script recorded it and carried on. The folder with a space caused no problem, and the caller's folder was unchanged afterwards.
Other commands and edge cases:
./in-each.sh projects test -d .git; echo "status $?"
./in-each.sh projects/api pwd; echo "status $?"
./in-each.sh nope ls; echo "status $?"
== api
== notes
-- failed with status 1
== old site
== site
Failed in 1 folder(s):
notes (status 1)
status 1
No subfolders in projects/api
status 0
./in-each.sh: line 16: pushd: nope: No such file or directory
status 1
test -d .git worked as a quick check for "is this a repository". projects/api has no visible subfolders (its .git folder is hidden), so nullglob produced an empty loop and the friendly message. A missing root stopped the script at the first pushd with status 1.
After the plain folder notes was moved out of projects, every remaining folder succeeded:
./in-each.sh projects git log --format='%s by %an' -1; echo "status $?"
== api
init by Ana
== old site
init by Ana
== site
init by Ana
Done: the command succeeded in all 3 folders.
status 0