This short post describes using a git alias for checking out branches like “I’m feeling lucky”, ie. the first branch matching the entered text gets checked out…

This makes sense working in a ticketing system for features, with a branch per ticket policy, where branches are often named [PROJECT CODE]-[TICKET NUMBER]-[FEATURE DESCRIPTION]

Instead of typing git checkout AWSM-1234-a-fantastic-feature I just want to address it by ticket number, or any unique text combination that I know of in the feature description.

So I put together a couple of aliases that can be included in the [alias] section of your .gitconfig file to make this easy

Git Lucky!

lucky = "!f() { git branch | grep -i " $1 " | head -1 | xargs -r git checkout; }; f"

(UPDATE: on some terminal’s you may need to omit the -r after xargs…)

lucky = "!f() { git branch | grep -i " $1 " | head -1 | xargs git checkout; }; f"

Using this you can check out the AWSM-1234-a-fantastic-feature branch with either

git lucky 1234


git lucky fantastic

Git Find

I’m pretty sure there are variants of this out there already, but this just shortcuts grokking through your branch list on your local repo to find a branch with some text

find = "!f() { git branch | grep -i " $1 "; }; f"

If I want to list all branches that contain the text ‘chart’ I can do git find chart and get that list

Personally this scratches an itch for me, I used to use git br | grep -i whatever and then git co, but being able to do it in one is pretty handy, and in quite a few cases, git lucky is all I need if I know something unique about the branch name.

For more info on setting up aliases and an explanation of the function syntax used for these commands, take a look at Phil Haacks great article on github flow aliases

Blog Logo

Stephen James

JavaScript and Front-End Developer


Proudly published with Hexo

Stephen James' Code Blog

Back to Overview