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.
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)'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With