pushd
and popd
: Navigating Directories Like a Pro
Summary
pushd
and popd
are powerful commands for navigating directories in Linux, allowing you to quickly switch between directories and easily return to previous locations. Think of them as a stack for directories!
Introduction
The pushd
and popd
commands work together to create a directory stack. pushd
pushes the current directory onto the stack and then changes the current directory to the directory specified as an argument. popd
removes the top directory from the stack and changes the current directory to that directory. This provides a convenient way to jump around the filesystem and easily return to previously visited directories without having to type out long paths repeatedly.
Use case and Examples
Changing Directory and Returning
The firstpwd
shows the current directory. pushd /etc/network
changes the current directory to /etc/network
and saves the original directory. The second pwd
shows the new current directory. popd
returns to the original directory. The third pwd
verifies that we are back in the starting directory. Pushing an Existing Directory
This pushes the current directory onto the stack and changes to/tmp
. If /tmp
doesn't exist, pushd
will give error message "pushd: no such file or directory". Rotating the Stack
If you have multiple directories on the stack, you can rotate the stack by using a number after the+
sign. pushd +1
rotates the stack so that the second directory becomes the top of the stack and the current working directory. Displaying the Directory Stack
Thedirs -v
command shows the directory stack. Each directory in the stack is listed with its index number. Commonly used flags
Flag | Description | Example |
---|---|---|
+N | Rotate the stack so that the Nth directory (starting from 0) becomes the top of the stack and becomes the current directory. | pushd +1 |
-N | Rotate the stack so that the Nth directory (starting from 0) becomes the top of the stack and becomes the current directory, but indexes from the right, starting with zero. | pushd -0 (equivalent to pushd +0 ) |
-n | Suppresses the normal change of directory when adding directories to the stack, so only the stack is manipulated. | pushd -n /tmp |
-q | Suppress output when manipulating the directory stack. | pushd -q /tmp |
dirs -l | Produce longer output; the default format uses a tilde to denote the user's home directory. Without this option, substitutions using the tilde character are not performed. | dirs -l |
dirs -p | Print the directory stack with one entry per line. | dirs -p |
dirs -v | Print the directory stack with one entry per line, preceded by its index in the stack. | dirs -v |