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

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

问题描述

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

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



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

  git show-ref | grep $(git show-ref -s  -  HEAD)| sed's。。* / \(。* \)| \1 |'| grep -v HEAD |排序| uniq 

它显示任何在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 show-ref -s -- HEAD) | sed 's|.*/\(.*\)|\1|' | grep -v HEAD | sort | uniq

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天全站免登陆