Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out which of 'master' or 'main' branches exists in a repository?

Tags:

git

branch

bash

I'm working on a Bash script that does some Git repository maintenance. Some of repositories use 'master' as the main branch while others use 'main'. What Git command can I use to return the first branch of these which exists?

P.S. I want to check local branches of a repo, since there will always be a local 'master' or 'main' branch.

like image 414
planetp Avatar asked Dec 30 '25 07:12

planetp


1 Answers

To find out which of the two local branches exists, you can use git branch with the -l/--list option:

git branch --list master main  # outputs 'master' or 'main', provided only one exists

Git also marks the current branch with an asterisk in the output, so for usage in a script you may want to add --format:

git branch --format '%(refname:short)' --list master main

To list all local branches, just omit --list and patterns:

git branch --format '%(refname:short)'
like image 153
Eugene Yarmash Avatar answered Jan 01 '26 00:01

Eugene Yarmash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!