Getting the Main Branch in Git

Pavel Saman
1 min readOct 10, 2022

--

How do you get the main branch in a repository?

There are a number of ways, let’s see three.

$ git remote show origin

This will give you more info, so you need to do a bit more parsing to get only the main branch:

$ git remote show origin | grep HEAD | sed -E 's/.*: (.*)$/\1/'

However, this gets the answer from the remote server, so it’s slow.

$ git symbolic-ref refs/remotes/origin/HEAD | sed 's@refs/remotes/origin/@@'

This one gets you an answer from your local repository, so it’s way faster.

Yet another way is:

$ git rev-parse --abbrev-ref origin/HEAD | sed 's@^origin/@@'

This one will also get you an answer locally, so it’s as fast as the previous one. In addition to the previous command, it requires less parsing.

Such things are sometimes useful, so it’s good to know, or know how to search for the answer :)

--

--

No responses yet