Fuzzy switching of git branches on cli, newest first.

(, en)

Even though there are plenty of UIs out there, I cannot get my self detached from the git commandline interface (cli). I cannot escape! It keeps a tight grip on me. Probably the best way out is the way forward, so why not make the cli more like the UI? Luckily, there are plenty of possibilities. One of them is to use fzf to select branches. On thing is certain: fzf for changed my life on the cli. I can combine it with z.lua (or the original) to jump to directories, I can use it in vim to select files, in the shell to wade through my history and to switch git branches. On the latter I want to focus here. This use case arose from working on a big project with many branches. Often I want to go back and forth between git branches, but I forgot the exact name, I only remember that I worked on it recently and probably a word contained in the branch name. (There are examples of using fzf with git branches, but I just could not find the right snippet that would satisfy my needs.)

asciicast

To get it running, you need to

  1. install fzf
  2. create git-fuzzy-branch in a directory that is part of your $PATH environment variable

    #!/usr/bin/env bash
    
    branches=$(git --no-pager branch --sort=-committerdate  -vv "$@" | grep -v "origin/HEAD") &&
    branch=$(echo "$branches" | fzf +m) && echo "$branch" &&
    git checkout $(echo "$branch" | perl -pE 's/^\W?\s+(?:origin\/)?(\S+)\s+.*$/\1/')
    
  3. make git-fuzzy-branch executable with chmod +x git-fuzzy-branch
  4. add an alias to your [alias] section in ~/.gitconfig
    [alias]
      # use fzf to select local branch
      fb = "!git-fuzzy-branch"
      # use fzf to select remote branch
      fbr = "!git-fuzzy-branch -r"
    

That’s it. Have fun!