Search code examples
gitgit-branchgit-alias

Alias git branches to replace "master" with "main"


I work on a bunch of different repos - many of them use master, and many of them use main.

I also have various shell aliases set up for git commands, e.g. gcm for git checkout master.

The problem is that I cannot use these aliases on repos where master doesn't exist. It's obviously not a big deal, because I just need to type out the command manually in that case, but it's slightly annoying.

I am wondering if there's a way I can "alias" branches in git, so when I say git push origin master it can just automatically replace that with main.


Solution

  • In a repository that has main, but not master, the simplest is to create a branch alias master that points to main:

    git symbolic-ref refs/heads/master refs/heads/main
    

    This gives the following list of branches (for example):

    $ git branch -a
    * main
      master -> main
      side
    

    Now everytime your commands reference master they apply to main. Even when you push master, the actual target is main:

    $ git push origin master
    Enumerating objects: 5, done.
    Counting objects: 100% (5/5), done.
    Writing objects: 100% (3/3), 241 bytes | 241.00 KiB/s, done.
    Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
    To ../gitupstream
       f57e131..15c1aad  master -> main