Git alias to checkout & pull the default branch of GitHub repositories
Matteo Mazzarolo
Posted on September 4, 2021
Short post here.
In my daily job, I switch between different projects/repositories quite often.
These projects can have different default branches (master
, main
, develop
), and they’re all GitHub repositories.
Something I do frequently is checking out the repositories’ default branch and pulling down the most recent updates.
Since I don’t remember what each repo’s default branch name is, I’m using a GitHub alias that automatically detects it:
# .gitconfig
[alias]
# checkout and pull the default branch
m = !git rev-parse --abbrev-ref origin/HEAD | cut -c8- | xargs -n 1 git checkout && git pull origin $(git rev-parse --abbrev-ref HEAD)
I invoke it with git m
.
It took me a bit to write this alias, mixing a few answers from this StackOverflow thread: git - how to get default branch?.
I went through some trial and error. I played with GitHub’s gh
CLI, git symbolic-ref
, and a few other options, but it looks like there’s no silver-bullet solution for this problem yet. Still, this command is working well for my use cases.
On the same topic, I’ve also found this reply to the “How to get the default for the master branch in Git?” StackOverflow question quite insightful.
Posted on September 4, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.