1

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
Chris Perry
  • 6,666
  • 3
  • 11
  • 21
  • 1
    `git branch` (and `git status`) do this "HEAD detached {at|from}..." dance by poking around in the reflogs, but there's nothing exported to let you do this from the command line. There probably should be; you could ask for it as a new Git feature (perhaps in rev-parse?), or work on it yourself and submit it to the mailing list. – torek Jun 26 '21 at 05:01

1 Answers1

3
git log -1 --pretty=%D

will print HEAD -> yourbranch if HEAD's an alias for i.e. attached to that branch tip, so git commit's update of HEAD will be redirected there, and just HEAD, yourbranch if HEAD and yourbranch both happen to be refs to the same commit, but HEAD isn't an alias for anything, updating the HEAD ref just updates the HEAD ref.

jthill
  • 55,082
  • 5
  • 77
  • 137
  • That's not quite what I want. I'm looking for a command that *only* outputs `yourbranch` – Chris Perry Jun 25 '21 at 20:16
  • 2
    Then restrict the decorations by adding `--decorate-refs=refs/heads/*`. Or if there's two branch tips pointing at the same commit and you're not attached to either of them you could check the reflogs to see if you used one or the other by name when you did your checkout. – jthill Jun 25 '21 at 20:46