After I’ve been working on a project for a while, I tend to have a list of multiple branches of work a repo. When jumping between branches on a project, my workflow is usually something like:

  1. git branch
  2. find the branch I want to jump to
  3. highlight the branch name in the terminal
  4. copy the branch name
  5. checkout the branch with git checkout <paste>

This isn’t too bad, but could it be better?

I’ve been using fzf to speed up my workflow on the command line and in vim (as a replacement for ctrlp) for a little while, but it recently occurred to me that you could also pipe fzf into a command.

This is extremely useful as you can use it to create an ad hoc UI for making a selection as part of a command.

The fzf utility gives us some new flexibility, now instead of needing to use my mouse to cut-and-paste the branch name I want, I can select the branch name using fzf.

After a little bit of experimentation, I came up with:

$ git for-each-ref --format='%(refname:short)' refs/heads | fzf | xargs git checkout

This oneline uses for-each-ref, a low-level command for scripting, to get a list of all the local branches in the repository without any decoration. The result is piped to fzf where we can select the branch we want and finally the result is passed through xargs so we can git checkout the branch.

The last step was to wrap this up in an git so it’s always avaialble to me from my gitconfig.

$ git config --global alias.cof $'!git for-each-ref --format=\''%\(refname:short\)\'' refs/heads | fzf | xargs git checkout'

In the above, I’ve configured cof for “checkout fuzzy” and I fought with the bash escape characters so you don’t have to.