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.

Steps to use the directory stack in Zsh:

  1. Open a Zsh session where the stack test can stay in one shell.
  2. Create a temporary workspace.
    $ mkdir -p /tmp/zsh-stack
  3. Enter the workspace before testing the stack.
    $ cd /tmp/zsh-stack
  4. Create two target directories inside the workspace.
    $ mkdir -p alpha beta
  5. 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.

  6. Print the numbered stack.
    $ dirs -v
    0	/tmp/zsh-stack/alpha
    1	/tmp/zsh-stack
  7. Push the second directory from the current location.
    $ pushd ../beta
  8. 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.

  9. Pop back to the previous directory.
    $ popd
  10. Verify that the shell returned to the first directory.
    $ print -r -- "${PWD:t}"
    alpha
  11. Leave the test workspace.
    $ cd /tmp
  12. Remove the temporary workspace.
    $ rm -rf /tmp/zsh-stack