如何获取Git中当前分支的名称?


当前回答

在终端中写入以下命令:

git branch | grep \*

or

git branch --show-current 

或Git 2.22及以上版本:

  git branch --show

其他回答

在Shell上,您可以执行以下操作

git branch | grep '*'

您还可以在当前项目的.git目录中看到当前分支的名称。

在终端中键入命令:open.git/HEAD输出文件包含当前分支的名称ref:refs/heads/{current_working_branch}

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

将仅显示分支名称

您可以永久设置bash输出以显示git分支名称。当您使用不同的分支时,它非常方便,无需一直键入$git状态。Github repo git-aware提示.

打开终端(ctrl-alt-t)并输入命令

mkdir ~/.bash
cd ~/.bash
git clone git://github.com/jimeh/git-aware-prompt.git

使用sudo nano~/.bashrc命令编辑.bashrc(适用于Ubuntu),并在顶部添加以下内容:

export GITAWAREPROMPT=~/.bash/git-aware-prompt
source "${GITAWAREPROMPT}/main.sh"

然后粘贴代码

export PS1="\${debian_chroot:+(\$debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] \[$txtcyn\]\$git_branch\[$txtred\]\$git_dirty\[$txtrst\]\$ "

在前面粘贴安装代码的同一文件的末尾。这将为您提供彩色输出:

从git的2.22版本开始,您可以使用:

git branch --show-current

根据手册页:

打印当前分支的名称。在分离HEAD状态下,不打印任何内容。