Photo by Samule Sun on Unsplash

A Utility For Finding Branches

Sugar on top of Oh My Zsh

Ilya Meerovich
2 min readAug 4, 2020

--

At work we have a convention for naming git branches that goes: dev/<your name>/<JIRA ticket id>. I often end up with a pile of branches of the form dev/ilyam/XY-1234, and having to switch between them gets to be a chore after a while.

Oh My Zsh definitely makes life easier by providing git autocomplete and some helpful aliases, but I thought I could save a couple more keystrokes still.

The script below is a bash function that takes a single argument. The output of git branch is grepped for that argument, and if no matching branch is found, the function echoes an error and exits. If a match is found then that branch will automatically get checked out, and if more than one match is found the user is shown all the options that they can then choose from, using the handy select command.

An interesting note is that git branch has a format argument to just list the branch names. The default behaviour of git branch without the argument is to prepend a * in front of the user's currently checked-out branch. This means that if the function returns a single match that also happens to be the current branch, you might end up trying to git checkout * somebranch which leads to unexpected results due to filename expansion.

For maximum results, name it whatever you like and stick it in your favourite shell config.

--

--