如何以编程方式确定当前签出的 Git 分支 [英] How to programmatically determine the current checked out Git branch
问题描述
在 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).
另请参阅我的相关问题:如何以编程方式确定 Git checkout 是否为标签,如果是,标签名称是什么?
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?
推荐答案
正确的解决方案是看一看 contrib/completions/git-completion.bash 为 __git_ps1
中的 bash 提示做这件事.删除所有额外的东西,比如选择如何描述分离的 HEAD 情况,即当我们在未命名的分支上时,它是:
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符号引用用于从符号引用中提取完全限定的分支名称;我们将它用于 HEAD,这是当前已检出的分支.
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.
替代解决方案可能是:
branch_name=$(git symbolic-ref -q HEAD)
branch_name=${branch_name##refs/heads/}
branch_name=${branch_name:-HEAD}
在最后一行我们处理分离的 HEAD 情况,使用简单的HEAD"来表示这种情况.
where in last line we deal with the detached HEAD situation, using simply "HEAD" to denote such situation.
2013 年 6 月 11 日添加
Junio C. Hamano(git 维护者)博客文章,以编程方式检查当前分支,从 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屋!