Skip to content

Instantly share code, notes, and snippets.

@darius-sas
Created May 12, 2021 08:08
Show Gist options
  • Save darius-sas/2aa85fe1e07cab572a0ddec3ee5d5c17 to your computer and use it in GitHub Desktop.
Save darius-sas/2aa85fe1e07cab572a0ddec3ee5d5c17 to your computer and use it in GitHub Desktop.
Get the main branch of a Git repository
# From https://stackoverflow.com/questions/55266918/how-to-get-main-git-branch-name-from-command-line
# Original author: tukusejssirs (StackOverflow)
# Current local branch name
git rev-parse --abbrev-ref HEAD
# Output: branch
# Remote branch name that is tracked by current local branch
git for-each-ref --format='%(upstream:short)' $(git symbolic-ref -q HEAD)
# Output: origin/branch
# Local main branch name
git branch -vv | grep -Po \
"^[\s\*]*\K[^\s]*(?=.*$(git branch -r | grep -Po "HEAD -> \K.*$").*)"
# Output: master
# Remote branch name that is tracked by local main branch
git branch -r | grep -Po "HEAD -> \K.*$"
# Output: origin/master
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment