如何在分离的 HEAD 状态下找到当前的 git 分支 [英] How to find the current git branch in detached HEAD state

查看:31
本文介绍了如何在分离的 HEAD 状态下找到当前的 git 分支的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过执行以下任一操作来找到当前的 git 分支名称:

git 分支 |awk '/^*/{ 打印 $2 }'git describe --contains --all HEAD

但是当处于分离的 HEAD 状态时,例如在 Jenkins maven 构建的后期构建阶段(或在 Travis git fetch 中),这些命令不起作用.

我目前的工作解决方案是这样的:

git show-ref |grep $(git log --pretty=%h -1) |sed 's|.*/(.*)|1|'|排序 -u |grep -v 头

它显示在其 HEAD 提示上有最后一次提交的任何分支名称.这很好用,但我觉得有更强大的 git-fu 的人可能有更好的解决方案?

解决方案

更瓷器的方式:

git log -n 1 --pretty=%d HEAD# 或等效地:git show -s --pretty=%d HEAD

引用将以 (HEAD, master) 格式列出 - 如果您打算在脚本中使用它而不是供人类使用,则必须稍微解析它.

你也可以自己更简洁地实现它:

git for-each-ref --format='%(objectname) %(refname:short)' refs/heads |awk "/^$(git rev-parse HEAD)/{print $2}"

好处是在不同的行中获取候选引用,没有额外的字符.

I can find the current git branch name by doing either of these:

git branch | awk '/^*/ { print $2 }'
git describe --contains --all HEAD

But when in a detached HEAD state, such as in the post build phase in a Jenkins maven build (or in a Travis git fetch), these commands doesn't work.

My current working solution is this:

git show-ref | grep $(git log --pretty=%h -1) | sed 's|.*/(.*)|1|' | sort -u | grep -v HEAD

It displays any branch name that has the last commit on its HEAD tip. This works fine, but I feel that someone with stronger git-fu might have a prettier solution?

解决方案

A more porcelain way:

git log -n 1 --pretty=%d HEAD

# or equivalently:
git show -s --pretty=%d HEAD

The refs will be listed in the format (HEAD, master) - you'll have to parse it a little bit if you intend to use this in scripts rather than for human consumption.

You could also implement it yourself a little more cleanly:

git for-each-ref --format='%(objectname) %(refname:short)' refs/heads | awk "/^$(git rev-parse HEAD)/ {print $2}"

with the benefit of getting the candidate refs on separate lines, with no extra characters.

这篇关于如何在分离的 HEAD 状态下找到当前的 git 分支的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆