什么是分离的头状态时发现当前的git分支名最简单的方法 [英] What is the simplest way to find the current git branch name when in detached HEAD state

查看:191
本文介绍了什么是分离的头状态时发现当前的git分支名最简单的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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, these commands doesn't work.

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

My current working solution is this:

git show-ref | grep $(git show-ref -s -- HEAD) | sed 's|.*/\(.*\)|\1|' | grep -v HEAD | sort | uniq

它显示在其头部端最后一次提交的任何分支名称。这工作得很好,但我觉得有人用更强的混帐福可能有一个prettier解决方案?

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?

推荐答案

一个更瓷器方式:

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.

这篇关于什么是分离的头状态时发现当前的git分支名最简单的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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