Jesper Rønn-Jensen
Jesper Rønn-Jensen

Reputation: 111576

Command to get the name of git's default branch

For scripting purposes I need to know the name of the "master" branch. I have some projects with the deprecated, old naming "master. I have other projects where the branch is named "main".

I would like to determine that name programatically. How do I find that name with a command?

One example I use a lot is to delete local branches that arez already merged to master (git branch --merged master | grep -v master |xargs git branch -d). In that case I need to provide either "main" or "master" as a value.

Upvotes: 2

Views: 714

Answers (2)

link
link

Reputation: 94

Try this command in a git repo

if git branch --all | grep -q master; then echo "'master' @ `pwd`"; else :; fi

If you do that, It prints out the directory path.

'master' @ /home/my_user/Documents/a-git-repo-with-master-name

You can use this do whatever you want. If it's main it doesn't print anything. If you need more functionality I can help you. Just let me know.

EDIT: For your specific case, if git branch --all | grep -q master; then git branch --merged master | grep -v master |xargs -I@ git branch -d @; else git branch --merged main | grep -v main |xargs -I@ git branch -d @; fi

Upvotes: 1

slebetman
slebetman

Reputation: 113878

Git has no concept of the main branch. Therefore what you want to do is not really possible.

Git users have a concept of the main branch and by general agreement among all git users (and general advice originally given by Linus Torvalds) this branch is normally called master but it does not have to be.

The reason the main branch can be given a name other than master is because git has no concept of the main branch.

Software created by other people such as Github or Bitbucket or Gitlab do have the concept of the main branch. If this is what you are asking you will need to use the APIs exposed by those software to find out which branch is the main branch. Of course you will need to know what service the developer is using in order to use its API.

For example for Github you can do this to get the main branch:

curl -H "Accept: application/vnd.github.v3+json" \ 
    https://api.github.com/repos/slebetman/httpstress |
    grep default_branch

However, using git alone it is not possible to do what you want because the concept of a main branch is does not exist in git - it is only a concept in the human brains of programmers.

Upvotes: 3

Related Questions