Hack 5. Use dirs, pushd and popd to manipulate directory stack
by Ramesh
You can use directory stack to push directories into it and later pop directory from the stack. Following three commands are used in this example.
- dirs: Display the directory stack
- pushd: Push directory into the stack
- popd: Pop directory from the stack and cd to it
Dirs will always print the current directory followed by the content of the stack. Even when the directory stack is empty, dirs command will still print only the current directory as shown below.
- # popd
- -bash: popd: directory stack empty
- # dirs
- ~
- # pwd
- /home/ramesh
How to use pushd and popd? Let us first create some temporary directories and push them to the directory stack as shown below.
- # mkdir /tmp/dir1
- # mkdir /tmp/dir2
- # mkdir /tmp/dir3
- # mkdir /tmp/dir4
- # cd /tmp/dir1
- # pushd .
- # cd /tmp/dir2
- # pushd .
- # cd /tmp/dir3
- # pushd .
- # cd /tmp/dir4
- # pushd .
- # dirs
- /tmp/dir4 /tmp/dir4 /tmp/dir3 /tmp/dir2 /tmp/dir1
- [Note: The first directory (/tmp/dir4) of the dir command output is always the current directory and not the content from the stack.]
At this stage, the directory stack contains the following directories:
- /tmp/dir4
- /tmp/dir3
- /tmp/dir2
- /tmp/dir1
The last directory that was pushed to the stack will be at the top. When you perform popd, it will cd to the top directory entry in the stack and remove it from the stack. As shown above, the last directory that was pushed into the stack is /tmp/dir4. So, when we do a popd, it will cd to the /tmp/dir4 and remove it from the directory stack as shown below.
- # popd
- # pwd
- /tmp/dir4
- [Note: After the above popd, directory Stack Contains:
- /tmp/dir3
- /tmp/dir2
- /tmp/dir1]
- # popd
- # pwd
- /tmp/dir3
- [Note: After the above popd, directory Stack Contains:
- /tmp/dir2
- /tmp/dir1]
- # popd
- # pwd
- /tmp/dir2
- [Note: After the above popd, directory Stack Contains: /tmp/dir1]
- # popd
- # pwd
- /tmp/dir1
- [Note: After the above popd, directory Stack is empty!]
- # popd
- -bash: popd: directory stack empty