Navigating through complex directory structures in a Linux terminal can become time-consuming, especially during system administration or scripting tasks. While cd (change directory) is the go-to command for directory navigation, it lacks the ability to manage a directory stack — a feature that pushd and popd bring to the table.
This article provides a deep dive into the pushd and popd commands, showing you how to streamline directory navigation and make your terminal workflows more efficient.
pushd (push directory) saves your current directory to a stack and then switches to a new directory.
popd (pop directory) removes the top directory from the stack and returns you to the previous one.
These commands are part of the directory stack mechanism available in bash, zsh, and other modern shells.
pushd and popd are invaluable when:
You frequently move between two or more directories.
You’re writing shell scripts that need to temporarily switch directories.
You want to avoid polluting your shell with unnecessary cd commands and maintain context.
Pushes the current directory onto the stack.
Changes directory to /path/to/target.
🔁 Example:
You’re now in /var/www/html, and your home directory ~ is stored on the stack.
Pops the top directory off the stack.
Returns you to the previous directory.
Continuing the example above:
You’re back in ~.
Use dirs to view the current state of the directory stack:
Sample output:
Index 0 is your current directory.
Higher indices represent earlier directories.
You can use:
to push the current directory to the stack without changing directories.
Efficient for iterative development without repetitive cd commands.
Here’s a script that builds code in a temporary directory and returns cleanly:
If the script fails inside /tmp/build-env, you still return to your original location.
This makes your scripts more maintainable, especially when errors occur — you can return to the original directory safely.
When working with multiple pushd calls, dirs -v helps trace your navigation history.
You can remove a specific directory from the stack:
Removes the directory at index 1 (not necessarily the current one).
Stack Overflow (not the site 😄): Using pushd excessively without corresponding popd calls can bloat your stack, leading to confusing directory state.
Not Available Everywhere: pushd and popd are built-ins in bash, zsh, and similar shells — they may not be available in minimal shells like sh.
Not Persistent: The directory stack is session-based. Once your terminal session ends, the stack resets.
In your .bashrc or .zshrc, add:
This reduces keystrokes and boosts productivity.