skip to content
Just Change Direction

Fuzzy git checkout

/ 2 min read

I find it a bit laborious to have to find, copy and then checkout my git branch all the time so I decided to write a little bash script to help me do it.

Here it is in action:

gif of a cli finding a branch and checking it out

First, I created a function that allows me to use fzf to fuzzy find the branch:

Terminal window
# Heavily inspired (read: copied) from: https://polothy.github.io/post/2019-08-19-fzf-git-checkout/
fuzzy-find-branch() {
# Checks you are in a workspace with git
git rev-parse HEAD >/dev/null 2>&1 || return
# Gets the list of branches and allows you to fuzzy search them
git branch --color=always --sort=-committerdate |
grep -v HEAD |
fzf --height 50% --ansi --no-multi |
sed "s/.* //"
}

I then use this function to select a branch inside a number of other functions which use the chosen branch to checkout, copy or delete the chosen branch. To make life easier I have these assigned to aliases e.g. gcof for fuzzy git checkout:

Terminal window
copy-branch() {
branch=$(fuzzy-find-branch)
print -s "$branch"
echo "$branch" | pbcopy
}
alias ggb=copy-branch
checkout-branch() {
branch=$(fuzzy-find-branch)
print -s "git checkout $branch"
git checkout "$branch"
}
alias gcof=checkout-branch
delete-branch() {
branch=$(fuzzy-find-branch)
print -s "git branch -d $branch"
git branch -d "$branch"
}
alias gdf=delete-branch

Hope it helps