在Unix或GNU脚本环境(例如Linux发行版、Cygwin、OSX)中,确定当前在工作目录中签出哪个Git分支的最佳方法是什么?
这种技术的一个用途是自动标记版本(就像svnversion对Subversion所做的那样)。
请参阅我的相关问题:如何以编程方式确定Git签出是否是标记,如果是,标记的名称是什么?
在Unix或GNU脚本环境(例如Linux发行版、Cygwin、OSX)中,确定当前在工作目录中签出哪个Git分支的最佳方法是什么?
这种技术的一个用途是自动标记版本(就像svnversion对Subversion所做的那样)。
请参阅我的相关问题:如何以编程方式确定Git签出是否是标记,如果是,标记的名称是什么?
当前回答
这是一个解。如果您将它添加到.bashrc中,它将在控制台中显示当前分支。
# git branch
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1) /'
}
$PS1="\$(parse_git_branch)$PS1"
然而,这是相当有限的。但是有一个叫做git sh的伟大项目,它正在做这些事情(甚至更多)。
其他回答
正确的解决方案是查看contrib/completions/git-completion。Bash在__git_ps1中为Bash提示符执行此操作。删除所有额外的内容,比如选择如何描述分离的HEAD情况,即当我们在未命名的分支上时,它是:
branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_name="(unnamed branch)" # detached HEAD
branch_name=${branch_name##refs/heads/}
Git symbol -ref用于从符号引用中提取完全限定的分支名称;我们将它用于HEAD,它目前已签出分支。
替代方案可以是:
branch_name=$(git symbolic-ref -q HEAD)
branch_name=${branch_name##refs/heads/}
branch_name=${branch_name:-HEAD}
在最后一行中,我们处理了分离的HEAD情况,简单地使用“HEAD”来表示这种情况。
增加了11-06-2013
Junio C. Hamano (git维护者)2013年6月10日的博客文章,以编程方式检查当前分支,更详细地解释了为什么(以及如何)。
将接受的答案调整为Windows powershell:
Split-Path -Leaf (git symbolic-ref HEAD)
如果你正在使用gradle,
```
def gitHash = new ByteArrayOutputStream()
project.exec {
commandLine 'git', 'rev-parse', '--short', 'HEAD'
standardOutput = gitHash
}
def gitBranch = new ByteArrayOutputStream()
project.exec {
def gitCmd = "git symbolic-ref --short -q HEAD || git branch -rq --contains "+getGitHash()+" | sed -e '2,\$d' -e 's/\\(.*\\)\\/\\(.*\\)\$/\\2/' || echo 'master'"
commandLine "bash", "-c", "${gitCmd}"
standardOutput = gitBranch
}
```
从这个答案:https://stackoverflow.com/a/1418022/605356:
$ git rev-parse --abbrev-ref HEAD
master
显然适用于Git 1.6.3或更新版本。
这个适合我。如果您希望返回纯字符串,那么——no-color部分非常重要。
git branch --no-color | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'