Pushd and popd for easy shell navigation
Navigating between many directories can be annoying when you have to type long path names. Imagine that you are in /home/you/work/project1/src, and you need to do some stuff in /home/you/notes/, then come back to your original working directory /home/you/work/project1/src. To do this you need to type the cd command three times, each time with a different path. To avoid this issue (or at least to minimize overhead of 'cd'ing around), I use pushd and popd.
What are pushd, popd
These are standard utilities that come with most unix/linux distributions. These utilities keep what is called a directory stack. As its name implies, the stack can store paths using a stack data structure. If you are familiar with stacks you should have understood the benefit by now.
When you do
pushd dir
You will change directory to dir and save dir in the stack. If you do another pushd dir2, then dir2 will be added on top of the directory stack.
Now typing the following command
popd
allows you to 'undo' your directory changes. By issuing a popd command, the last directory pushed in the stack (which is your current directory) will be removed, you will change directory to the second directory which becomes the at the top of the stack.
Also, at any time, you can type
dirs -v
to see what are the contents of the directory stack.
Adopting pushd and popd
To make it more natural to use, I created two functions in my .bashrc. One function uses pushd to overwrite the 'cd' command and the other function creates a new 'p' command using popd.
These are the two functions
function cd { pushd $1 >/dev/null clear ls -l } function p { popd clear ls -l }
When I type 'cd dir', the current directory is changed to whatever directory I indicated. Before that however, the current directory is saved in the directory stack. When I want to go back to where I was before the 'cd' command, I just type 'p'. So basically, pushd and popd allows you to implement 'undo' for cd operations, which saves you a lot of time when navigating in the shell.
| Labels: unix, howto |
|

Comment