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.
Related: How to manage Bash command history
Related: How to create and use aliases in Bash
Steps to use the directory stack in Bash:
- 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
- Print the starting directory.
$ pwd /tmp/bash-guides/use-directory-stack
- 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.
- Show the stack with numbered entries.
$ dirs -v 0 /tmp/bash-guides/use-directory-stack/app 1 /tmp/bash-guides/use-directory-stack
- 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
- 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.
- Pop the top entry to return to the previous directory.
$ popd /tmp/bash-guides/use-directory-stack/app /tmp/bash-guides/use-directory-stack
- Verify the active directory after the pop.
$ pwd /tmp/bash-guides/use-directory-stack/app
- Pop once more to return to the starting directory.
$ popd /tmp/bash-guides/use-directory-stack
- Move outside the temporary tree.
$ cd /tmp
- Remove the temporary directories.
$ rm -r /tmp/bash-guides
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.