Linux Tips 7: Pushd and popd command how to for easy directory traversal

Moving around directories can sometimes be a real pain in Linux/Unix/OS X. With more descriptive directory names and source code trees that group all sub-folders in a MVC pattern means that you will often need to jump between three or more directories to edit the one page in your application. Therefore it is very important to be able to quick jump between directories. One way is to always start at the base and re-launch your cd commands from history. The alternative is to use the Linux command to enable quick traversal between directories of interest.

The basic commands in this how to are: pushd and popd. They work based on the concept of a stack and you can cd into directories using pushd, which adds the new directory on to the stick, and return to previously visited directories using popd. An example is shown below:

[1014 paul:~] pushd Downloads/
~/Downloads ~
[1015 paul:~/Downloads] pushd ~/Documents/Contracting/
~/Documents/Contracting ~/Downloads ~
[1016 paul:~/Documents/Contracting] dirs -v
0 ~/Documents/Contracting
1 ~/Downloads
2 ~
[1017 paul:~/Documents/Contracting] popd
~/Downloads ~
[1018 paul:~/Downloads] popd
[1019 paul:~]

The above code shows me going from my home directory (~) and navigating to my downloads folder, then my contracting folder. You can see with each pushd command it is giving me a view of the stack, with the most recently executed pushd target on top (top being left most). You can also explicitly view the stack by executing the dirs -v command. Finally I use two popd
commands to pop items off the stack which brings me back to my home directory.


Post a Comment