Jumping to frequently used folders and automating environment setups

From Stat DS Computing Wiki


When you have several different projects to manage, it's likely that each of them has different requirements in terms of environment, packages installed, and so on. Ideally, all of these environments should be isolated from each other in order to avoid problems with dependencies. A simple example of this happens with Python projects, which should have dedicated conda or venv environments.

The goal of this simple guide is to show how to setup simple bash scripts that allow to quickly jump between different projects by automatically changing folders and activating the correct environment via a custom single-word command (an alias). N.B. All of the code in the snippets below should be in your .bashrc or .zshrc  files.

The first step is to setup a so-called mark. At a high level, this is basically a pointer that marks the project directory and tells the system where to move from an arbitrarily different directory. This can be set by simply typing mark in the project directory. The simple functions that do this are

export MARKPATH=$HOME/.marks
function mark {
        mkdir -p "$MARKPATH"; ln -s "$(pwd)" "$MARKPATH/$1"
}
function unmark {
        rm -i "$MARKPATH/$1"
}
function marks {
        # for linux (currently commented out)
        # ls -l "$MARKPATH" | sed 's/  / /g' | cut -d' ' -f9- | sed 's/ -/\t-/g' && echo

        # for mac
        \ls -l "$MARKPATH" | tail -n +2 | sed 's/  / /g' | cut -d' ' -f9- | awk -F ' -> ' '{printf "%-10s -> %s\n", $1, $2}'
}

After this we can setup the jump command to move around the filesystem to previously set marks.

function jump {
       cd -P "$MARKPATH/$1" 2>/dev/null || echo "No such mark: $1"
}

The last step is to simply setup an alias that jumps to the correct mark and activate the relevant (in this case Python with Conda) environment:

alias CUSTOM_NAME="jump MARK_NAME; conda activate ENVIRONMENT_NAME"