Check if a git branch is ahead of another using a script

自古美人都是妖i 提交于 2019-12-05 18:51:47

You can use

git log branch2..branch1

If branch1 has no commit ahead of branch2, output will be empty.

You can also use git rev-list --count branch2..branch1

This will show the number of commits ahead

Source

You have already got an answer. So I'll add something more.

git cherry command can be used to do this.

git cherry branch1 branch2

This will list the commits which are in branch2, but not in branch1. You can use the -v flag to make it print the commit message along with the hash if you want.

git cherry -v branch1 branch2

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

Hope it helps :)

matthiasbe's answer is fine for many purposes, but for scripting, as long as your Git is not too severely ancient,1, you would generally want to use:

if git merge-base --is-ancestor commit-specifier-1 commit-specifier-2; then
    # commit specifier #1 is an ancestor of commit specifier 2
else
    # commit specifier #1 is NOT an ancestor of commit specifier 2
fi

as the test. This is because git merge-base --is-ancestor encodes the result as its exit status, so that you do not have to run a separate test to compare the number to something.

Note that it is possible for one branch tip to be both ahead of and behind another:

$ git rev-list --left-right --count stash-exp...master
1       6473

Here, neither specified commit is an ancestor of the other. However, given these other specifiers:

$ git rev-list --left-right --count master...origin/master
0       103

we see that master here is strictly behind origin/master, so that:

$ git merge-base --is-ancestor master origin/master && echo can fast-forward
can fast-forward

which is the same answer you would get from seeing the zero count out of git rev-list --count origin/master..master:

$ git rev-list --count origin/master..master
0

1git merge-base --is-ancestor was introduced in Git version 1.8.0. Some systems are still shipping with Git 1.7...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!