Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have branch1 and branch2 and I want some sort of:

git branch1 isahead branch2

That will show if branch1 has commits that branch2 doesn't have (and possibly specify those commits too). I can't check diff cause branch2 is ahead of branch1 (has commits that branch1 doesn't have).

Is there a way? I looked through git diff and couldn't find anything

like image 935
omer mazig Avatar asked Jul 23 '18 09:07

omer mazig


3 Answers

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

like image 167
matthiasbe Avatar answered Oct 13 '22 18:10

matthiasbe


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...

like image 29
torek Avatar answered Oct 13 '22 18:10

torek


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 :)

like image 4
Nimeshka Srimal Avatar answered Oct 13 '22 18:10

Nimeshka Srimal