DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Git alias to checkout & pull the default branch of GitHub repositories
Matteo Mazzarolo
Matteo Mazzarolo

Posted on • Originally published at mmazzarolo.com on

Git alias to checkout & pull the default branch of GitHub repositories

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)
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)

🌚 Life is too short to browse without dark mode