如何以编程方式确定当前签出的Git分支 [英] How to programmatically determine the current checked out Git branch

查看:186
本文介绍了如何以编程方式确定当前签出的Git分支的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在UNIX或GNU脚本环境(比如一个Linux发行版,Cygwin的,OSX),什么是确定的Git分支的工作目录目前已签出的最佳方式?

一个使用这种技术会自动标记释放(如 svnversion,如果将与Subversion一样)。

One use of this technique would be automatically labeling a release (like svnversion would do with Subversion).

请参见我的有关问题:<一href=\"http://stackoverflow.com/questions/1593188/how-to-programmatically-determine-whether-the-git-checkout-is-a-tag-and-if-so-wh\">How以编程方式确定一个Git检出是否是一个标记,如果有什么是标签的名字吗?

Please also see my related question: How to programmatically determine whether a Git checkout is a tag, and if so what is the tag name?

推荐答案

正确的解决办法是采取偷看<一个href=\"http://git.kernel.org/?p=git/git.git;a=blob;f=contrib/completion/git-completion.bash;hb=HEAD\">contrib/completions/git-completion.bash这是否在 __ git_ps1 bash提示符。删除所有临时演员就像选择怎么形容分离的头的情况下,即当我们对不愿透露姓名的分支,它是:

The correct solution is to take a peek at contrib/completions/git-completion.bash does that for bash prompt in __git_ps1. Removing all extras like selecting how to describe detached HEAD situation, i.e. when we are on unnamed branch, it is:

branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_name="(unnamed branch)"     # detached HEAD

branch_name=${branch_name##refs/heads/}

git的象征-REF 是用来提取充分从象征性的参考资格的分支机构名称;我们使用它的头,这是目前已签出的分支。

git symbolic-ref is used to extract fully qualified branch name from symbolic reference; we use it for HEAD, which is currently checked out branch.

替代的解决方案可能是:

Alternate solution could be:

branch_name=$(git symbolic-ref -q HEAD)
branch_name=${branch_name##refs/heads/}
branch_name=${branch_name:-HEAD}

在那里我们处理分离的头的情况下,使用简单的头来表示这样的情况下最后一道防线。

where in last line we deal with the detached HEAD situation, using simply "HEAD" to denote such situation.

补充2013年11月6日

JUNIO C.滨野(GIT维护者)的博客文章,<一个href=\"http://git-blame.blogspot.com/2013/06/checking-current-branch-programatically.html\">Checking当前分支编程的,从2013年6月10日介绍的个为什么(和怎么样了)的更多细节。

Junio C. Hamano (git maintainer) blog post, Checking the current branch programatically, from June 10, 2013 explains whys (and hows) in more detail.

这篇关于如何以编程方式确定当前签出的Git分支的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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