Mark & Jump!

First post of 2013! Time really flies when working at a startup :-) Today’s post is about a set of cool little bash functions that I found really help my productivity.

Have you ever been working on different code bases some of which are deeply nested? I have, and usually I would setup some symlinks in my home directory and use those to switch between all the places I needed to be, but sometimes I forget the syntax for ln, or I’m in a directory and change to another only to realize I need to jump back. Well if you have found yourself in a similar situation, fear not! For I have a solution.

Add the following to your favorite shell initializition location (.bashrc or .profile, etc):

#!/bin/bash

export MARKPATH=$HOME/.marks
function jump {
    cd -P $MARKPATH/$1 2>/dev/null || echo "No such mark: $1"
}
function mark {
    mkdir -p $MARKPATH; ln -s "$(pwd)" $MARKPATH/$1
}
function unmark {
    rm -i $MARKPATH/$1
}
function marks {
    ls -l $MARKPATH | sed 's/  / /g' | cut -d' ' -f9- | sed "s/ -/ -/g" && echo
}

function _jump {
    local cur=${COMP_WORDS[COMP_CWORD]}
    local marks=$(find "${MARKPATH}/${cur}"* -maxdepth 0 -type l -o -type d | awk -F "${MARKPATH}/" '{print $NF}')
    COMPREPLY=($(compgen -W '${marks[@]}' -- "$cur"))
    return 0
}

complete -o default -o nospace -F _jump jump

Lets take a walk through this code and make sure we understand what it does.

  • First we declare this is a bash script.
  • Then we define where we would like to store our marks. A mark is a symlink to a directory we would like to frequently navigate to.
  • Jump takes a parameter and supports autocomplete.
  • Mark creates the symlink and makes it available to jump
  • Unmark removes a previously marked directory
  • Marks lists the marks we have already created

Putting it all together into something we can use:

%> cd /var/tmp/jump-test/this/is/a/very/long/directory
%> mark useful
%> mkdir test
%> cd ~/
%> jump useful

We can also use the autocomplete functionality to jump within a directory

%> jump useful/test

That’s it, feel free to mark and jump anywhere!

Image: Flicker, [Laura Mardon] (http://www.flickr.com/photos/powpapowpow/5017850049/)

blog comments powered by Disqus