git - how to get default branch?

前端 未结 9 2069
轻奢々
轻奢々 2020-12-04 17:44

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

相关标签:
9条回答
  • 2020-12-04 18:04

    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.

    0 讨论(0)
  • 2020-12-04 18:06

    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
    
    0 讨论(0)
  • 2020-12-04 18:07

    Seems like a bit of a workaround solution but this seems to work:

    $ cat .git/refs/remotes/origin/HEAD 
    ref: refs/remotes/origin/master
    
    0 讨论(0)
  • 2020-12-04 18:08

    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.

    0 讨论(0)
  • 2020-12-04 18:09

    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.

    0 讨论(0)
  • 2020-12-04 18:15

    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
    
    0 讨论(0)
提交回复
热议问题