pushd Command

The pushd command in Linux is a shell built-in that allows you to manipulate the directory stack. It saves the current working directory on a stack and then changes the current directory to a new one. This is incredibly useful for navigating between frequently used directories without typing full paths repeatedly.

Syntax

pushd [dir]
pushd [+N | -N]

Description

The directory stack is a list of directories that you can quickly switch between. pushd adds a directory to the top of this stack and makes it the current working directory. The popd command is used to remove directories from the stack and change back to a previous directory.

Common uses include:

  • Temporarily switching to a directory and easily returning.
  • Managing a list of frequently accessed project directories.
  • Automating navigation in shell scripts.

Common Options

Option Description
+N Rotates the stack so that the Nth directory (counting from the left of the list printed by dirs, starting with 0) becomes the current directory.
-N Rotates the stack so that the Nth directory (counting from the right of the list printed by dirs, starting with 0) becomes the current directory.

Examples

Add a directory to the stack and change to it

pushd /var/log
# Output: ~/documents /var/log

Changes to /var/log and adds the previous directory to the stack.

View the directory stack

dirs
# Example Output: /var/log /home/user/documents

Displays the directories currently in the stack.

Return to the previous directory (and remove from stack)

popd
# Output: /home/user/documents

Removes the top directory from the stack and changes to the next one.

Rotate the stack and change directory

pushd +1
# If stack was: /dirA /dirB /dirC # After pushd +1: /dirB /dirC /dirA

Rotates the stack to make the Nth directory the current one.

See also