Skip to content

Instantly share code, notes, and snippets.

@sergray
Created September 9, 2014 10:04
Show Gist options
  • Save sergray/885a3eb128b20cb7aedd to your computer and use it in GitHub Desktop.
Save sergray/885a3eb128b20cb7aedd to your computer and use it in GitHub Desktop.
checkout git branch by substring
#!/usr/bin/env python
"Checkout git branch with name substring"
from __future__ import print_function
import sys
from subprocess import check_output
def main(branch_name):
check_output(['git', 'fetch', 'origin'])
remote_branches = check_output(['git', 'branch', '-r']).split()
matching_branches = [branch.decode('utf-8') for branch in remote_branches if branch_name in branch]
if not matching_branches:
print('no matching branches')
sys.exit(1)
if len(matching_branches) > 1:
print('several branches match:', matching_branches)
sys.exit(1)
branch_name = matching_branches[0].rsplit('/')[-1]
check_output(['git', 'checkout', branch_name])
check_output(['git', 'pull', '--ff-only'])
if __name__ == '__main__':
main(sys.argv[1])
@natepisarski
Copy link

Awesome script my man! Found it super helpful. I tend to work with tens of branches at a time, all starting with a 6-digit number. This really sped that workflow up.

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