git - how to get default branch?

My team alternates between usage of dev and master as default branch for several repos and I would like to write a script that checks for the default branch when entering a directory.

When pull requests are opened in some of these repos, they either default to 'dev' or 'master' as the merge target.

I understand how to set this information but not retrieve it: https://help.github.com/articles/setting-the-default-branch/

Is there a git command available to determine default branch for remote repository?


Solution 1:

I found a way to detect the default-branch if it is not master.

git remote show [your_remote] | sed -n '/HEAD branch/s/.*: //p'

I tested it with multiple repo from gitlab, and it worked fine. (for the most situations [your_remote] will be origin, run git remote to check the name of your remote)

Solution 2:

Tested with git 2.9.4 (but possibly works in other versions) in a repo cloned from Github:

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

Solution 3:

git rev-parse --abbrev-ref origin/HEAD will print origin/<default-branch-name>. The git symbolic-ref answers are doing the same thing but need a longer argument.

If the origin repository changes its default branch name, then git remote set-head origin -a will retrieve the new default branch name.

Solution 4:

This question is a bit old but in case anyone comes across this more recently...

git remote show <remote_name> | awk '/HEAD branch/ {print $NF}'

That will also only display the branch name, not including any of the whitespace or other nonsense.

I like to save this using a couple git aliases (I have a bunch of useful aliases like this):

upstream-name = !git remote | egrep -o '(upstream|origin)' | tail -1
head-branch = !git remote show $(git upstream-name) | awk '/HEAD branch/ {print $NF}'

I use "upstream" and "origin" as my remotes almost 100% of the time ("upstream" when I go with a Fork & Pull workflow... which is often). Your use case may not need the upstream-name alias, I just find it useful.