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:
- find the branch I want to jump to
- highlight the branch name in the terminal
- copy the branch name
- checkout the branch with
git checkout <paste>
This isn’t too bad, but could it be better?
This is extremely useful as you can use it to create an ad hoc UI for making a selection as part of a command.
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
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.