How to Detect the Default Branch in a git Repository

By  on  

Over the past few years, many engineering teams have switched their default git branch name from master to a different, potentially less offensive term. I'm all for choosing to name your default branch whatever you'd like, but not having a universal default branch name can complicate some automation.

So how can we detect the default branch name for a git repository? I use a few chained commands:

git remote show REMOTE_REPO_NAME | grep 'HEAD branch' | cut -d' ' -f5

Swap out REMOTE_REPO_NAME with the name of the remote/ upstream repository and you'll get the remote repository's default branch name!

Recent Features

  • By
    Create a CSS Flipping Animation

    CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...

  • By
    Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

Incredible Demos

  • By
    iPad Detection Using JavaScript or PHP

    The hottest device out there right now seems to be the iPad. iPad this, iPad that, iPod your mom. I'm underwhelmed with the device but that doesn't mean I shouldn't try to account for such devices on the websites I create. In Apple's...

  • By
    Create WordPress Page Templates with Custom Queries

    One of my main goals with the redesign was to make it easier for visitors to find the information that was most popular on my site. Not to my surprise, posts about MooTools, jQuery, and CSS were at the top of the list. What...

Discussion

  1. Djangounet

    Cool trick ! Except… it works only if your LANG is “en”…

    My attempt :

    git remote show origin | grep 'HEAD' | cut -d':' -f2 | sed -e 's/^ *//g' -e 's/ *$//g'
    

    Best regards

  2. WA

    This one should be language-neutral:

    git ls-remote --symref https://github.com/cli/cli HEAD | awk -F'[/\t]' 'NR == 1 {print $3}'
    
    
  3. sp

    Hi,
    How to find default branch for all the repositories in an organization ?

  4. Alex Z

    Hi, thanks for it!

    I digged a bit further on git remote and I noticed in its man page the subcommand git remote set-head. Its description begins with “Sets or deletes the default branch (i.e. the target of the symbolic-ref refs/remotes//HEAD)”.

    So, it turns out that we can actually do this:

    $ sed -e ‘s/^.*\///’ < .git/refs/remotes/origin/HEAD
    devel

    It is way faster than actually querying the remote server.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!