pushd
Command in Linux
Summary
The pushd
command in Linux allows you to change the current directory and save the previous directory for easy return. It's part of the shell's directory stack management.
Introduction
The pushd
command is a built-in shell command in Linux environments. It's designed to simplify navigating between directories, particularly when working across multiple projects or nested directory structures. It essentially combines changing directories (cd
) with storing the previous directory on a stack, allowing you to easily return to it later using popd
. This helps to avoid having to type out long directory paths repeatedly.
Use case and Examples
Basic Usage: Change directory and save previous one
This command changes the current directory to/var/log
and saves the previous directory onto the directory stack. Changing to a directory relative to the current directory
If you're in/var/log
, this command changes the directory to /var/log/apache2
and pushes /var/log
onto the stack. Swapping the top two directories on the stack
This rotates the stack, effectively swapping the top two directory entries. If the stack is/home /var /tmp
, after running this, the stack becomes /var /home /tmp
and the current directory is /var
. Accessing the directory stack
Usedirs -v
to view the directory stack with numbered indexes. This can be helpful to figure out which index to use with the pushd +n
command. Returning to the previous directory using popd
This command removes the top directory from the stack and changes the current directory to that directory. If the directory stack was/var/log /home
, popd
will change the current directory to /home
and remove /var/log
from the stack. Commonly used flags
Flag | Description | Example |
---|---|---|
+N | Rotates the stack so that the Nth directory (counting from the left of the list shown by dirs , starting at zero) is at the top of the stack and changes to that directory. | pushd +2 (Brings the third directory in the stack to the top and changes to it.) |
-N | Rotates the stack so that the Nth directory (counting from the right of the list shown by dirs , starting at zero) is at the top of the stack and changes to that directory. | pushd -1 (Brings the second last directory in the stack to the top and changes to it.) |
No argument | If no arguments are supplied, pushd exchanges the top two elements of the directory stack, making the second element the new current directory. Same as pushd +1 |