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
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.
There doesn't seem to be an answer that doesn't require cloning so far
This requires git 2.8.0 or newer
$ git ls-remote --symref git@github.com:pre-commit/pre-commit.github.io HEAD
ref: refs/heads/real_master HEAD
e100a6a3c72b4e54f0d176f791dfd2dbd7eb5fa7 HEAD
Seems like a bit of a workaround solution but this seems to work:
$ cat .git/refs/remotes/origin/HEAD
ref: refs/remotes/origin/master
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.
I found a way to detect the default-branch if it is not master.
git remote show [your_remote] | grep "HEAD branch" | cut -d ":" -f 2
I tested it with multiple repo from gitlab, and it worked fine.
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