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?
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.
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.
Oldest comments (5)
They way I’ve been dealing with switching between branches is this:
git checkout ~first-to-letters-or-more~ TAB
After pressing TAB, it should autocomplete. Even If your branches have similar names, you can easily select which one you want.
Nice! I do tend to also do that when the branch names are pretty simple. The few use cases that I find the
fzfmethod particularly helpful for are:
In both of these cases, finding the right match might be difficult with a prefix search!
Hmm, I didn’t take those cases into account. I guess here comes my lack of experience.
Thank you for sharing!
Please don't apologize! I didn't clearly write out the use cases where this would be useful or detail the specific parts of
fzfthat make it unique. Your feedback helps me improve my writing and my communication.
Thank you for the comments!
Hi Kyle. Thanks for sharing. I am been searching a solution to efficiently checkout a branch. This is looks super useful and I am going to integrate this into my workflow. :)
May I suggest a small modification. Using
git branch --sort=-committerdatereturns a sorted list of branches based on the commit date. No need to scan the full list. Recent branches are at the top.