How to navigate around directories in Linux easily

If you are working in Linux, in command line interface may it be server administration or embedded Linux development, you often will navigate between directories to make changes to files and configurations etc. Keeping track of a particular directory and going back and forth between them can be time consuming if you have to type the complete path by hand. You may resort for middle click of the mouse or Alt+Insert key combination. But they may not work in all conditions. For this situation there are bunch of tools to get the advantage. They are pushd, popd and dirs command. They are part of the bash internals and if you are using bash then you do not need to install anything else.

Now let use see how it works. It basically works like a stack, where you add items to a stack and take back what you recently added or in other words Last In First Out.

#Assume that you navigate to a folder, a long path
cd /usr/share/doc/bash
#Now you want to kind of bookmark location for later visit.
then you push the folder to the stack
pushd .
#then you want to stack another folder you can do like this.
pushd /usr/share/doc/bash-completion
$ dirs -v
 0 /usr/share/doc/bash-completion
 1 /usr/share/doc/bash
 2 ~
#Now the current directory has been automatically changed to the in which was in the stack.
#if you run popd it will jump to next item of the stack

You can use the dirs index number for programming purpose to like
the example given below.

dirs -v
 0 ~
 1 /usr/share/doc/bash-completion
 2 /usr/share/doc/bash
 3 ~
cp test.txt /usr/share/doc/bash-completion/
#is same as 
cp test.txt ~1/
Another example would be
cp $(dirs +2) /tmp
cp ~2  /tmp


Leave a Reply

Your email address will not be published. Required fields are marked *