在Unix或GNU脚本环境(例如Linux发行版、Cygwin、OSX)中,确定当前在工作目录中签出哪个Git分支的最佳方法是什么?

这种技术的一个用途是自动标记版本(就像svnversion对Subversion所做的那样)。

请参阅我的相关问题:如何以编程方式确定Git签出是否是标记,如果是,标记的名称是什么?


当前回答

有人提到在bash中做不到三个任务…像这样混乱的控制流怎么样:

branch_name="$(b=$(git symbolic-ref -q HEAD); { [ -n "$b" ] && echo ${b##refs/heads/}; } || echo HEAD)"

其他回答

如果您正在使用旧的NT命令行,您可以使用以下命令:

@for /f "usebackq" %i in (`git symbolic-ref -q HEAD`) do @echo %~ni

要在批处理文件中使用,你必须将%加倍:

@for /f "usebackq" %%i in (`git symbolic-ref -q HEAD`) do @echo %%~ni

我在bash文件中使用了这个方法。

git branch | grep '^*' | sed 's/* //'  


################bash file###################
#!/bin/bash
BRANCH=$(git branch | grep '^*' | sed 's/* //' )
echo $BRANCH

我发现调用git相当慢(任何子命令), 特别是更新提示符。在顶级机器(raid 1, 8 gb ram, 8个硬件线程)上,回购根目录内的时间变化在0.1到0.2秒之间,而在回购外部的时间变化在0.2秒以上。不过,它确实运行Cygwin。

因此,为了提高速度,我写了这个脚本:

#!/usr/bin/perl

$cwd=$ENV{PWD}; #`pwd`;
chomp $cwd;

while (length $cwd)
{
        -d "$cwd/.git" and do {
                -f "$cwd/.git/HEAD" and do {
                        open IN, "<", "$cwd/.git/HEAD";
                        $_=<IN>;
                        close IN;
                        s@ref: refs/heads/@@;
                        print $_;
                };
                exit;
        };

        $cwd=~s@/[^/]*$@@;
}

可能需要一些调整。

正确的解决方案是查看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日的博客文章,以编程方式检查当前分支,更详细地解释了为什么(以及如何)。

如果你正在使用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
            }

```