git/list[1] front-page[2] threads[3] people[4] search[5] about
 

Re: How to get the branch HEAD points to using a plumbing command?

From
Ævar Arnfjörð Bjarmason <avarab@gmail.com>
Date
Jan 5, 2021, 15:24 UTC
Message-ID
<8735zfs8xj.fsf@evledraar.gmail.com>
In-Reply-To
<132D030A-AAD3-4EFC-9858-7EA39503A746@gmail.com>
On Tue, Jan 05 2021, Utku wrote:
Show 15 quoted lines
> If HEAD points to a branch, then `cat .git/HEAD` returns (at least on my Git version):
>
>     ref: refs/heads/2.x
>
> So, to understand which branch HEAD points to, I can:
>
> - Read file contents of `.git/HEAD`.
> - Try to match the contents with the regular expression `^ref: refs\/heads\/(.*)$`. If the capturing group is not empty, then HEAD points to the branch indicated by the capturing group. Otherwise, HEAD does not point to a branch.
>
> To do this using only plumbing commands, I came up with:
>
> - Run `git show-ref --head --heads`.
> - Parse the output first by newlines, then by spaces and test if the commit hash of HEAD is present in other lines. If it is, then extract the branch name and return it. If not, return empty string.
>
> My question is, is there a "better" (more idiomatic, less "expensive", etc.) way of doing it using only one plumbing command? This solution is OK but it is more work than just matching one line with a regular expression. The reason I want to do this using only plumbing commands is because I think that plumbing command interface would be more stable than the format (organization, structure) of files under the `.git/` directory across Git versions. Please correct me if I'm wrong in this idea as well.
You'll want to use git-rev-parse for this, e.g.:
    $ git rev-parse --symbolic-full-name HEAD
    refs/heads/master
Previous: UtkuNext: Jeff King
Message 2 of 4 in “How to get the branch HEAD points to using a plumbing command?”
  1. UtkuJan 5, 2021
  2. Ævar Arnfjörð BjarmasonJan 5, 2021
  3. Jeff KingJan 5, 2021
  4. Junio C HamanoJan 5, 2021

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.