How to use the directory stack in Bash

The Bash directory stack keeps a short list of working directories inside the current shell, so a terminal can move between related paths without retyping each absolute path. It fits interactive work where editing source files, reading logs, and returning to a project root happen in the same shell session.

The pushd builtin changes directory and puts the previous location on the stack. The dirs -v command shows numbered stack entries with the current directory at index 0, and popd removes the top entry so Bash returns to the directory beneath it.

The stack belongs to the shell session that created it, so entries do not persist after that shell exits. The command sequence uses temporary directories and default Bash builtins only, then removes the test tree after the stack behavior is confirmed.

Steps to use the directory stack in Bash:

  1. Create two directories for the stack test and enter the working directory.
    $ mkdir -p /tmp/bash-guides/use-directory-stack/app /tmp/bash-guides/use-directory-stack/logs
    $ cd /tmp/bash-guides/use-directory-stack
  2. Print the starting directory.
    $ pwd
    /tmp/bash-guides/use-directory-stack
  3. Push into the first directory.
    $ pushd app
    /tmp/bash-guides/use-directory-stack/app /tmp/bash-guides/use-directory-stack

    Bash prints the directory stack after a successful pushd command.

  4. Show the stack with numbered entries.
    $ dirs -v
     0  /tmp/bash-guides/use-directory-stack/app
     1  /tmp/bash-guides/use-directory-stack
  5. Push into a second directory from the current location.
    $ pushd ../logs
    /tmp/bash-guides/use-directory-stack/logs /tmp/bash-guides/use-directory-stack/app /tmp/bash-guides/use-directory-stack
  6. Confirm that the newest directory is at the top of the stack.
    $ dirs -v
     0  /tmp/bash-guides/use-directory-stack/logs
     1  /tmp/bash-guides/use-directory-stack/app
     2  /tmp/bash-guides/use-directory-stack

    Use dirs -v before popd when several stack entries are present and the next return point is not obvious.

  7. Pop the top entry to return to the previous directory.
    $ popd
    /tmp/bash-guides/use-directory-stack/app /tmp/bash-guides/use-directory-stack
  8. Verify the active directory after the pop.
    $ pwd
    /tmp/bash-guides/use-directory-stack/app
  9. Pop once more to return to the starting directory.
    $ popd
    /tmp/bash-guides/use-directory-stack
  10. Move outside the temporary tree.
    $ cd /tmp
  11. Remove the temporary directories.
    $ rm -r /tmp/bash-guides