Directory Stack with pushd, popd, and dirs

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 150 of 205

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 DIR changes to DIR and adds it to the top of the stack, keeping the old folder below it;
  • popd removes the top entry and changes to the folder that is now on top;
  • dirs shows 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

FormEffect
pushd DIRgo to DIR, put it on top of the stack
pushdswap the two top entries (go to the previous folder)
pushd +Nrotate the stack so that entry N (counted from the top) comes to the top
pushd -Nthe same, counting from the bottom (-0 is the last entry)
pushd -n DIRadd 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

FormEffect
popdremove the top entry and go to the new top
popd +Nremove entry N (counted from the top) without changing folder, unless N is 0
popd -Nremove entry N counted from the bottom
popd -nremove 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

FormEffect
dirsthe stack on one line, home folder as ~
dirs -vone entry per line, with numbers
dirs -pone entry per line, without numbers
dirs -lfull paths instead of ~
dirs +Nonly entry N
dirs -cclear 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
NeedTool
go back to the folder you just leftcd -
toggle between two folderscd - or pushd
remember several folders and return in reverse orderpushd and popd
jump among a fixed set of folders by numberdirs -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;
  • pushd fails 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). -u and pipefail stay 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 pushd puts the root on top of the starting folder; inside the loop, pushd adds the project folder and popd returns to the root; the final popd returns 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 in status immediately, before popd changes $?.
  • -- after pushd protects against folder names that begin with a dash.
  • The failed array (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

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Directory Stack with pushd, popd, and dirs and get answers drawn from it.

Signed-in readers only.