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

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

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


当前回答

试一试:

 git symbolic-ref --short -q HEAD

或者你试着用git分支——no-color force简单的纯字符串输出:

 git branch  --no-color

当grep处于正则模式(-E)时,你可以检查字符'*'是否存在:

 git branch  --no-color  | grep -E '^\*' 

结果类似于:

* currentBranch

你可以使用下面的选项:

sed 's/\*[^a-z]*//g'
cut -d ' ' -f 2
awk '{print $2}'

例如:

 git branch  --no-color  | grep -E '^\*' | sed 's/\*[^a-z]*//g'
 git branch  --no-color  | grep -E '^\*' | sed cut -d ' ' -f 2
 git branch  --no-color  | grep -E '^\*' | awk '{print $2}'

如果存在错误,您不能使用默认值:

  cmd || echo 'defualt value';

全部放入一个bash函数中:

function get_branch() {
      git branch --no-color | grep -E '^\*' | awk '{print $2}' \
        || echo "default_value"
      # or
      # git symbolic-ref --short -q HEAD || echo "default_value";
}

Use:

branch_name=`get_branch`;
echo $branch_name;

其他回答

这是一个解。如果您将它添加到.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日的博客文章,以编程方式检查当前分支,更详细地解释了为什么(以及如何)。

使用——porcelain提供了一个易于解析的向后兼容输出:

Git status——branch——porcelain | grep '##' | cut -c 4-

从文档中可以看到:

瓷格式类似于短格式,但保证不会在Git版本之间或基于用户配置以向后不兼容的方式更改。这使得它非常适合通过脚本进行解析。

https://git-scm.com/docs/git-status

结果与单行变量赋值中接受的答案相同:

branch_name=$((git symbolic-ref HEAD 2>/dev/null || echo "(unnamed branch)")|cut -d/ -f3-)

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

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