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

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

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


当前回答

将接受的答案调整为Windows powershell:

Split-Path -Leaf (git symbolic-ref HEAD)

其他回答

我发现调用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@/[^/]*$@@;
}

可能需要一些调整。

将接受的答案调整为Windows powershell:

Split-Path -Leaf (git symbolic-ref HEAD)

我在这里尝试最简单和最不言自明的方法:

git status | grep "On branch" | cut -c 11-

我是这样做的:

git branch | sed --quiet 's/* \(.*\)/\1/p'

输出如下所示:

$ git branch | sed --quiet 's/* \(.*\)/\1/p'
master
$

我发现了两种非常简单的方法:

$ git status | head -1 | cut -d ' ' -f 4

and

$ git branch | grep "*" | cut -d ' ' -f 2