Skip to content

Instantly share code, notes, and snippets.

@zdennis
Last active June 5, 2019 16:12
Show Gist options
  • Save zdennis/240c9a4e1028422f07df to your computer and use it in GitHub Desktop.
Save zdennis/240c9a4e1028422f07df to your computer and use it in GitHub Desktop.
Git checkout alias that accepts regular expressions
[alias]
co = !"find_and_checkout_branch(){\
for last; do true; done ; \
pattern='^/.*/$' ;\
if [[ $# -eq 1 && $last =~ $pattern ]] ;\
then \
branch_pattern=`echo $last | sed -e 's/^\\///' -e 's/\\/$//'` ;\
branch=`git for-each-ref --sort=-committerdate --format='%(refname:short)' refs/heads/ | grep -E $branch_pattern | head -n1` ;\
if [[ $branch ]] ; then \
git checkout $branch ;\
else \
echo "No branch found matching $last" ; \
exit 1 ; \
fi \
else \
git checkout $@ ;\
fi \
} ; find_and_checkout_branch"

The below co alias allows you to pass in a basic regular expression (specified by a leading and ending /) for checking out a recently worked on branch. Falls back to normal checkout behavior if the given branch name isn't a regex.

Example

With regex:

git co /cool-feature/
Switched to branch 'spike/1234/cool-feauture'

With regex, no matching branch:

git co /non-existent/
No branch found matching /non-existent/

Without regex:

git co spike/1234/cool-feauture

It works as expected (at least how I expect it to work) with multiple arguments:

git co -b my-new-branch-here
git co -b my-new-branch-here parent-branch-here

If you provide more than one argument it doesn't use regular expression matching.

@ajhekman
Copy link

ajhekman commented Mar 9, 2015

nice!

@zdennis
Copy link
Author

zdennis commented Mar 9, 2015

gist updated to keep working with multiple arguments, e.g.:

git co -b my-new-branch-here
git co -b my-new-branch-here parent-branch-here

If you provide more than one argument it doesn't use regular expression matching.

@kevinawoo
Copy link

I made it case insensitive by changing grep to grep -E -i $branch_pattern

Also, if you have git bash completion installed, add this to your .bash_profile

function _git_co() {
  _git_checkout
}

@ddddavidmartin
Copy link

ddddavidmartin commented Sep 17, 2015

For my work I often haven to open remote branches as well. I have extended the script so that:

  • if no local branch is found, the remote branches are checked
  • if there is a matching remote branch, the user is asked whether it should be opened; confirm with 'y' or abort with any other input

The reason for making it interactive is that there are usually a lot more remote branches to pick from, and it can end up matching the wrong one. This way the user can confirm before actually checking it out. Works quite well for me.

I forked the alias here: https://gist.github.com/githubbrowser/7dff9354c841cc51663b

@lnguyen639
Copy link

Awesome post!
To githubbrowser, thanks for the update, works great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment