I have no deep knowledge of git
, however, in git
, there is usually {remote}/HEAD
, e.g. origin/HEAD
. Here’s an excerpt from the man page of git remote
:
set-head
Sets or deletes the default branch (i.e. the target of the
symbolic-ref refs/remotes/<name>/HEAD) for the named remote.
Having a default branch for a remote is not required, but allows
the name of the remote to be specified in lieu of a specific
branch. For example, if the default branch for origin is set to
master, then origin may be specified wherever you would normally
specify origin/master.
From this I understand that the {remote}/HEAD
is the main/default branch of the {remote}
. One could get the name of the branch using this (does anyone know a better/plumbing command?):
git branch -r | grep -Po 'HEAD -> \K.*$'
origin/master
When one wants to get the local main/default branch, there usually is no HEAD
branch, however usually there’s one and only branch that tracks the {remote}/HEAD
, which name we can get using (again, there surely is a better command):
git branch -vv | grep -Po "^[\s\*]*\K[^\s]*(?=.*$(git branch -rl '*/HEAD' | grep -o '[^ ]\+$'))"
master
Of course, one need to set-head
if it is not already set, in order to have a ‘HEAD
/master/main branch’ in the output of git remote -r
. Therefore, we need to run the following command once prior to using the above commands (thanks for pointing this out @pixelbrackets).
git remote set-head origin -a
Update:
Recently, I wanted to get some more information (some commands I’ve got from here):
# Get currently checked out local branch name
git rev-parse --abbrev-ref HEAD
# Output: branch
# Get remote branch name that is tracked by currently checked out local branch
git for-each-ref --format='%(upstream:short)' "$(git symbolic-ref -q HEAD)"
# Output: origin/branch
# Get local main branch name
git branch -vv | grep -Po \
"^[\s\*]*\K[^\s]*(?=.*$(git branch -rl '*/HEAD' | grep -o '[^ ]\+$'))"
# Output: master
# Get remote branch name that is tracked by local main branch (AKA the remote HEAD branch)
git branch -r | grep -Po 'HEAD -> \K.*$'
# Output: origin/master