Home > Software engineering >  Bash git ls-remote know which is the main branch
Bash git ls-remote know which is the main branch

Time:09-09

I use the following command to know all the remote branches of a project:

git ls-remote https://github.com/nanashili/AuroraEditor --h --sort origin "refs/heads/*" | sed "s,.*${TAB}refs/heads/,,"

But I would like to know which is the main branch of the project, which can be different from main and master.

Can you give me a hand?

CodePudding user response:

git ls-remote -q --symref <remote> | head -1

prints where the HEAD points at in the remote repository. <remote> can be a name like origin or an URL. To cut the full ref name out of the result run

git ls-remote -q --symref <remote> | awk 'NR==1 { print $2; }'

NR==1 selects Record Number 1 (the first line); $2 prints the second field of the 3 space/tab-separated fields. If you want to cut the short branch name instead of the full:

git ls-remote -q --symref <remote> | awk 'NR==1 { print $2; }' | sed 's!^refs/heads/!!'

Example:

$ git ls-remote -q --symref https://github.com/nanashili/AuroraEditor | awk 'NR==1 { print $2; }' | sed 's!^refs/heads/!!'
development-main

Or avoiding awk completely:

git ls-remote -q --symref <remote> | head -1 | cut -f1 | sed 's!^ref: refs/heads/!!'

CodePudding user response:

Plain Git doesn't have a term as main branch. In GitHub, for example, you can choose main, but it will be used on GitHub servers only, your git repository will not change. So to solve the problem, you can make main branch configurable in your script using config file or arguments.

CodePudding user response:

Understanding that the main branch can be any branch in a repo, the only thing that can get you close to know what branch is the main branch would be (I think) by checking HEAD from the remote, then check the branches in the remote and see which branch is on that revision.... the problem is that there might be more than one branch pointing at that revision.

  • Related