The directory stack lets Zsh move between nearby working directories while keeping previous locations available in the same shell session. It fits source-tree work, log review, and configuration changes that bounce between two or three paths.
The pushd command changes to a target directory and stores the previous $PWD below it. dirs -v prints numbered stack entries with index 0 as the active directory, and popd removes the current entry so the shell moves back to the next one.
The example uses a temporary workspace with two child directories and removes it at the end. The commands need one Zsh session because the directory stack is shell-local; a new terminal, subshell, or script starts with its own stack.
Related: How to set Zsh shell options
Related: How to manage PATH with the Zsh path array
Steps to use the directory stack in Zsh:
- Open a Zsh session where the stack test can stay in one shell.
- Create a temporary workspace.
$ mkdir -p /tmp/zsh-stack
- Enter the workspace before testing the stack.
$ cd /tmp/zsh-stack
- Create two target directories inside the workspace.
$ mkdir -p alpha beta
- Push the first directory onto the stack.
$ pushd alpha
pushd makes alpha the active directory and keeps the previous workspace directory as the next stack entry. Interactive Zsh echoes the stack after pushd unless shell options suppress that display; the numbered dirs -v output in the next step is the checkpoint to compare.
- Print the numbered stack.
$ dirs -v 0 /tmp/zsh-stack/alpha 1 /tmp/zsh-stack
- Push the second directory from the current location.
$ pushd ../beta
- Check the stack before returning to an earlier directory.
$ dirs -v 0 /tmp/zsh-stack/beta 1 /tmp/zsh-stack/alpha 2 /tmp/zsh-stack
The entry at index 0 is the active directory. A plain popd returns to the entry currently shown at index 1.
- Pop back to the previous directory.
$ popd
- Verify that the shell returned to the first directory.
$ print -r -- "${PWD:t}" alpha - Leave the test workspace.
$ cd /tmp
- Remove the temporary workspace.
$ rm -rf /tmp/zsh-stack
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.