Git - how to get the default branch?

My command alternates between using dev and master as the default branch for multiple repositories, and I would like to write a script that checks the default branch when entering the directory.

When download requests are opened in some of these repositories, they default to setting "dev" or "master" as the merge target.

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

Is there a git command to define the default branch for a remote repository?

+17
source share
7 answers

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 
+18
source

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

 git remote show [your_remote] | grep "HEAD branch" | cut -d ":" -f 2 

I tested it with several repos from gitlab and it worked fine.

+11
source

Is there a git command to define the default branch for a remote repository?

No, it seems not:

 git ls-remote -v https://github.com/<user>/<repo> 

This will be a list of all branches, but not HEAD (which is symref, which stands for the default branch)

Similarly, the GitHub Help API may display headers, but will also not include HEAD.

+3
source

There is an option - short for git symbolic-ref . Therefore, my preferred command:

 $ git symbolic-ref --short HEAD master 
+3
source

This works for me with Git 2.1.10 using the repository cloned from GitHub:

 git branch -r --points-at refs/remotes/origin/HEAD 

The main problem with this approach is that it lists each remote branch pointing to HEAD; however, the output includes a hint:

  origin/HEAD -> origin/master origin/master origin/test123 

So, you can post-process the output with grep or similar to find one that has an arrow:

 git branch -r --points-at refs/remotes/origin/HEAD | grep '\->' | cut -d' ' -f5 | cut -d/ -f2 
+1
source

This seems like a bit of a workaround, but it works:

 $ cat .git/refs/remotes/origin/HEAD ref: refs/remotes/origin/master 
0
source

There seems to be no answer that does not yet require cloning.

This requires git 2.8.0 or later.

 $ git ls-remote --symref git@github.com :pre-commit/pre-commit.imtqy.com HEAD ref: refs/heads/real_master HEAD e100a6a3c72b4e54f0d176f791dfd2dbd7eb5fa7 HEAD 
0
source

Source: https://habr.com/ru/post/982870/


All Articles