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.

@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