Bash tips: Easier git branch checkouts

Following on from my tip to easily delete git branches, here’s a way to checkout a branch matching against a pattern, for when you can’t remember the actual name of a branch.

I’ve also added a little extra functionality to try and checkout a remote branch if there is no matching branch locally.

function git_checkout_like() {
MATCHING_LOCAL_BRANCH=$(git for-each-ref --format='%(refname:strip=2)' refs/heads/* | grep $1)
if [ -n "$MATCHING_LOCAL_BRANCH" ]
then
git checkout $MATCHING_LOCAL_BRANCH
else
# try and find a matching remote branch
git for-each-ref --format='%(refname:strip=3)' refs/remotes/** | \
grep $1 | \
xargs git checkout
fi
}

As before, I’ve aliased this to something short:

alias gcl=git_checkout_like

Now I can checkout with ease!

$ git branch
* master
my-feature
my-other-feature
$ gcl other
Switched to branch 'my-other-feature'
$ git branch -r
origin/HEAD -> origin/master
origin/master
origin/coworkers-feature-that-he-wants-you-to-check
$ gcl coworkers
Branch coworkers-feature-that-he-wants-you-to-check set up to track remote branch coworkers-feature-that-he-wants-you-to-check from origin.
Switched to a new branch 'coworkers-feature-that-he-wants-you-to-check'

Caveats

If there is more than one branch that matches your pattern you’ll get an error. I did think about just checking out the first available branch that matches the pattern, but as it might not be the branch you were after I decided to leave it out.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade