I don’t always remember exact names of branches in repositories I’m working on, so I wrote a function for checking out branches based on searching roughly for the name.

Example usage

$ git branch
fix_argument_exception
fix_null_pointer_exception
implement_new_feature_xyz
* master
obscure_branch_name

$ qc xyz
Switched to branch 'implement_new_feature_xyz'

$ qc exception
[Multiple branches matching search terms]
fix_argument_exception
fix_null_pointer_exception

$ qc point ex
Switched to branch 'fix_null_pointer_exception'

The script

qc() {
    for term in "$@"
    do
        local regex="${regex}${term}.*"
    done

    local branches=$(git for-each-ref  refs/heads/ --format="%(refname:short)" | grep "$regex" --ignore-case)
    local num_matches=$(echo "$branches" | wc -l)

    if [ $num_matches -eq 1 ]; then
        git checkout $branches 2>&1
        return
    elif [ $num_matches -gt 1 ]; then
        echo "[Multiple branches matching search terms]"
        echo "$branches"
        return
    else
        echo "No branches found matching search terms"
    fi
}