Sometimes it can be painful to navigate the Linux file system with commands, especially for the newbies. Normally, we primarily use the cd (Change Directory) command for moving around the Linux file system.
In a previous article, we reviewed a simple yet helpful CLI utility for Linux called bd – for quickly moving back into a parent directory without typing cd ../../.. repeatedly.
This tutorial will explain a related set of commands: “pushd” and “popd” which are used for efficient navigation of the Linux directory structure. They exist in most shells such as bash, tcsh etc.
How pushd and popd Commands Work in Linux
pushd and popd work according to the “LIFO” (last in, first out) principle. In this principle, only two operations are allowed: push an item into the stack, and pop an item out of the stack.
pushd adds a directory to the top of the stack and popd removes a directory from the top of the stack.
To display directories in the directory stack (or history), we can use the dirs command as shown.
Dirs – Display Directories in Directory
pushd command – puts/adds directory paths onto a directory stack (history) and later allowing you to navigate back to any directory in history. While you add directories to the stack, it also echoes what’s existing in history (or “stack”).
The commands show how pushd works:
pushd – Add Directories to Stack
From directory stack in the output above (directory index is in reverse order):
- /var/log is the fifth [index 0] in the directory stack.
/Desktop/ is fourth [index 1].
/Documents/ is third [index 2].
is first [index 4].
Optionally, we can use the directory index in the form pushd +# or pushd -# to add directories to the stack. To move into
/Documents, we would type:
pushd – Directory Navigation with Number
Note after this, the stack content will change. So from the previous example, to move into /var/www/html, we would use:
pushd – Navigate Directory with Number
popd command – removes a directory from the top of the stack or history. To list the directory stack, type:
To remove a directory from the directory stack inded use popd +# or popd -# , in this case, we would type the command below to remove
popd – Remove Directory from Stack
In this tutorial we explained “pushd” and “popd” commands which are used for efficient navigation of the directory structure. Share your thoughts concerning this article via the feedback form below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.