pushd
In Linux, pushd is a command used to manage the directory stack, which is a stack of directories that allows users to quickly navigate back and forth between directories. It works in conjunction with the popd command, which pops the top directory off the stack, and dirs, which shows the contents of the stack. The pushd command adds the current directory to the stack and then changes to a new directory, making it useful for temporary changes in the directory that you can easily return from.
Key Points:
Directory Stack: The directory stack is a list of directories stored in memory, enabling users to go back to a previous directory using the
popdcommand.pushd Syntax:
pushd <directory>If no argument is given,
pushdswaps the current directory with the top of the stack (it essentially returns you to the previous directory).If a directory is specified, it is pushed onto the stack, and the working directory changes to the specified directory.
Example 1: Basic usage of pushd
Let’s say you are in a directory /home/user and you want to navigate to /tmp and then easily come back to /home/user.
Current directory:
$ pwd /home/userUse
pushdto change to/tmp:$ pushd /tmp /tmp ~ /home/userAfter running
pushd, the output shows that/home/useris added to the stack, and the current directory is changed to/tmp.Check the directory stack:
$ dirs /tmp ~ /home/userThe
dirscommand shows that/tmpis the top of the stack, and/home/useris the second entry.Return to the previous directory:
$ popd /home/userThe
popdcommand pops the top directory off the stack (which was/tmp), returning you to the previous directory, which is/home/user.
Example 2: Using pushd with no argument
When you run pushd with no arguments, it swaps the current directory with the top directory on the stack.
Current directory:
$ pwd /home/userUse
pushdto change to/tmp:$ pushd /tmp /tmp ~ /home/userNow, use
pushdwith no argument:$ pushd /home/user ~ /tmpThe
pushdcommand swapped the current directory/tmpwith/home/user, putting/home/userback at the top of the stack.
Example 3: Using pushd with a relative directory
You can also use pushd with relative paths. Let's assume you're in /home/user and want to go to /home/user/projects, a subdirectory.
Current directory:
$ pwd /home/userUse
pushdwith a relative directory:$ pushd projects /home/user/projects ~ /home/userHere,
projectsis a subdirectory of/home/user, andpushdtook you to/home/user/projectswhile adding/home/userto the stack.
Summary
pushdchanges your working directory and adds the previous one to a stack.The stack allows easy navigation back to previous directories with
popd.You can check the contents of the stack with the
dirscommand.Running
pushdwithout an argument swaps your current directory with the top directory in the stack.
This is very useful for complex navigation scenarios, especially when you need to work in multiple directories but want to easily return to where you started.