Consistent Handling of Git Repositories With Different Default Branches

submited by
Style Pass
2023-09-18 08:00:15

Typically, I develop on a feature branch, and when the feature is ready, there is an obvious branch into which I want to merge the branch. This branch is often called master', main' or `develop'. During development, I will occasionally rebase my feature branch on top of this branch, to reduce future merge conflicts, and to avoid falling behind on changes merged by other developers. I will call this branch the default branch from here on.

To make common operations consistent across repositories, I want to use a `git default-branch' command that returns the name of the default branch, so that I can use commands like

What I consider the default branch in the examples above is the HEAD of the remote repository (usually on GitHub). I use the remote name origin for the remote containing the latest version of the default branch. If your naming is different, adapt the commands accordingly.

The command remote show origin provides all relevant information about the remote, including the HEAD branch which can be filtered out with git remote show origin | sed -n '/HEAD branch/s/.*: //p'. The downside of this approach is that it queries the remote, so it will take quite a long time due to network latency, and will only work if you are online.

Leave a Comment