Updating git aliases for different default branch names
If you’re like me, you might have set up some aliases for common tasks in git. Some of my aliases are shorthand for things like checking out the main branch of a repository.
In my aliases, I had some hard-coded assumptions around what this branch name would be.
# .gitconfig
[alias]
cm = checkout master
While this will work when the branch is named master
, it won’t work when the default branch is named something else.
There is now a lot of steam behind changing the default branch name away from master
to something more inclusive. GitHub, GitLab, and BitBucket have all made commitments to changing.
The good news for you is that there is a simple fix for this.
First, here’s a bonus tip for you. You can create sub-shells in your git aliases. It’s as simple as starting the alias with !
then writing a command as if you were in a shell.
If you would write echo 'hi there'
in your shell, the alias would look like:
# .gitconfig
[alias]
hi = ! echo 'hi there'
The way to get the default branch in a repo is to use symbolic-ref
. Docs for this can be found here.
Using this, we can easily see what the HEAD
branch is called, and update our alias like this:
# .gitconfig
[alias]
cm = !git checkout $(git symbolic-ref --short HEAD)
Now it’s a lot more resilient and you can use the same shortcut, no matter what a repo owner decides to call their primary branch.