I was wondering if there's a way to output only the name of a remote git branch when the HEAD is detached after checking it out.
Right now I'm following the steps in How to get the current branch name in Git?, but this only works when you're in a non-detached HEAD. In a detatched HEAD, commands like git rev-parse --abbrev-ref HEAD
will simply output "HEAD".
The closest I can get to showing the branch name is running git branch
, which shows the current branch as * (HEAD detached at {remote-name}/{branch-name})
.
This is perfectly fine for practical purposes, but my curiosity is getting the better of me, and I'm wondering if there's a command that would simply output only the name of the originating branch, rather than the context prefacing it.
I would also like to develop a better understanding of why the HEAD is detaching when I go through these steps.
Workflow
This situation comes up when I'm checking out a remote branch for purposes of PR review. Here are the commands I'm running to get to this scenario:
> git remote add {name for this remote} {git url}
> git fetch {name for this remote}
> git checkout remotes/{remote-name}/{branch name}
> git branch