Search code examples
linuxbashgitbranchgit-branch

Bash git ls-remote know which is the main branch


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?


Solution

  • 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/!!'