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

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
    # 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.

@mmazzarolo - Aug 28, 2021