且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何以编程方式确定当前签出的 Git 分支

更新时间:2023-02-16 10:10:29

正确的解决方案是看一看 contrib/completions/git-completion.bash__git_ps1 中的 bash 提示做这件事.删除所有额外的东西,比如选择如何描述分离的 HEAD 情况,即当我们在未命名的分支上时,它是:

The correct solution is to take a peek at contrib/completions/git-completion.bash does that for bash prompt in __git_ps1. Removing all extras like selecting how to describe detached HEAD situation, i.e. when we are on unnamed branch, it is:

branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_name="(unnamed branch)"     # detached HEAD

branch_name=${branch_name##refs/heads/}

git符号引用用于从符号引用中提取完全限定的分支名称;我们将它用于 HEAD,这是当前已检出的分支.

git symbolic-ref is used to extract fully qualified branch name from symbolic reference; we use it for HEAD, which is currently checked out branch.

替代解决方案可能是:

branch_name=$(git symbolic-ref -q HEAD)
branch_name=${branch_name##refs/heads/}
branch_name=${branch_name:-HEAD}

在最后一行我们处理分离的 HEAD 情况,使用简单的HEAD"来表示这种情况.

where in last line we deal with the detached HEAD situation, using simply "HEAD" to denote such situation.

2013 年 6 月 11 日添加

Junio C. Hamano(git 维护者)博客文章,以编程方式检查当前分支,从 2013 年 6 月 10 日开始,更详细地解释了为什么(以及方法).

Junio C. Hamano (git maintainer) blog post, Checking the current branch programatically, from June 10, 2013 explains whys (and hows) in more detail.