且构网

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

给定提交ID,如何确定当前分支是否包含提交?

更新时间:2023-01-28 13:35:17

有多种方法可以实现此结果.第一个天真的选择是使用git log并使用grep搜索特定的提交,但这并不总是精确的

There are multiple ways to achieve this result. First naive option is to use git log and search for a specific commit using grep, but that is not always precise

git log | grep <commit_id>

***直接使用git branch来使用

git branch --contains $COMMIT_ID

下一步是找出当前分支,自git 1.8.1开始使用

The next step is finding out current branch which can be done since git 1.8.1 using

git symbolic-ref --short HEAD

并合并为

git branch $(git symbolic-ref --short HEAD) --contains $COMMIT_ID

但是上面的命令不会返回true或false,并且有一个较短的版本,如果提交在当前分支中,则返回退出代码0;否则,则返回退出代码1

But the command above doesn't return true or false and there is a shorter version that returns exit code 0 if commit is in current branch OR exit code 1 if not

git merge-base --is-ancestor $COMMIT_ID HEAD

退出代码很好,但是当您想要字符串truefalse作为答案时,您需要添加一些内容,然后与bash中的if结合使用

Exit code is nice, but as you want string true or false as answer you need to add a bit more and then combined with if from bash you get

if [ 0 -eq $(git merge-base --is-ancestor $COMMIT_ID HEAD) ]; then echo "true"; else echo "false"; fi