Bash directory bookmarks

While reading through the comments to this Habrahabr article (in Russian), I came across an excellent tip for the directory bookmarks in bash shell.  Here’s how to set it up.

Firstly, add the following lines to your .bashrc or .bash_profile file:

# Bash Directory Bookmarks
# From: http://habrahabr.ru/post/151484/#habracut
alias m1='alias g1="cd `pwd`"'
alias m2='alias g2="cd `pwd`"'
alias m3='alias g3="cd `pwd`"'
alias m4='alias g4="cd `pwd`"'
alias m5='alias g5="cd `pwd`"'
alias m6='alias g6="cd `pwd`"'
alias m7='alias g7="cd `pwd`"'
alias m8='alias g8="cd `pwd`"'
alias m9='alias g9="cd `pwd`"'
alias mdump='alias|grep -e "alias g[0-9]"|grep -v "alias m" > ~/.bookmarks'
alias mload='source ~/.bookmarks'
alias ah='(echo;alias | grep "g[0-9]" | grep -v "m[0-9]" | cut -d" " -f "2,3"| sed "s/=/ /" | sed "s/cd //";echo)'

Secondly, if you are already using ~/.bookmarks file for anything, change the two references to it in the above lines to some other file.  It’s where your directory bookmarks will be stored.

Thirdly, if you prefer to save the bookmarks between your bash sessions, add the “mload” command to the end of your .bashrc or .bash_profile file, and “mdump” to your .bash_logout file.

Start a new bash shell and you are all set.

Using this setup is extremely easy.  Navigate to the directory that you want to bookmark, and save it under the numbered bookmark:

$ cd /var/www/html
$ m1

When you want to navigate back to that folder, simply call the numbered bookmarks:

$ g1

If you need to refresh your memory, issue “ah” command (think: aliases help), and it will print out the list of your current numbered bookmarks with the directory paths associated with them.

In case you need more than nine bookmarks, simply extend the lines in your .bashrc or .bash_profile file to run through more numbers, or use some other bookmark naming convention that works for you.

Enjoy.

P.S.: A quick Google search points to the author’s page, which links to a more advanced solution – bashmarks.

Leave a Comment