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.

  1. # popd
  2. -bash: popd: directory stack empty
  3.  
  4. # dirs
  5. ~
  6.  
  7. # pwd
  8. /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.

  1. # mkdir /tmp/dir1
  2. # mkdir /tmp/dir2
  3. # mkdir /tmp/dir3
  4. # mkdir /tmp/dir4
  5.  
  6. # cd /tmp/dir1
  7. # pushd .
  8.  
  9. # cd /tmp/dir2
  10. # pushd .
  11.  
  12. # cd /tmp/dir3
  13. # pushd .
  14.  
  15. # cd /tmp/dir4
  16. # pushd .
  17.  
  18. # dirs
  19. /tmp/dir4 /tmp/dir4 /tmp/dir3 /tmp/dir2 /tmp/dir1
  20.  
  21. [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:

  1. /tmp/dir4
  2. /tmp/dir3
  3. /tmp/dir2
  4. /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.

  1. # popd
  2. # pwd
  3. /tmp/dir4
  4.  
  5. [Note: After the above popd, directory Stack Contains:
  6. /tmp/dir3
  7. /tmp/dir2
  8. /tmp/dir1]
  9.  
  10. # popd
  11. # pwd
  12. /tmp/dir3
  13.  
  14. [Note: After the above popd, directory Stack Contains:
  15. /tmp/dir2
  16. /tmp/dir1]
  17.  
  18. # popd
  19. # pwd
  20. /tmp/dir2
  21.  
  22. [Note: After the above popd, directory Stack Contains: /tmp/dir1]
  23.  
  24. # popd
  25. # pwd
  26. /tmp/dir1
  27.  
  28. [Note: After the above popd, directory Stack is empty!]
  29.  
  30. # popd
  31. -bash: popd: directory stack empty