Fuzzy switching of git branches on cli, newest first.
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 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.)
To get it running, you need to
- install fzf
git-fuzzy-branchin a directory that is part of your
#!/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/')
chmod +x git-fuzzy-branch
- add an alias to your
[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!