git: programmatically know by how much the branch is ahead/behind a remote branch

后端 未结 10 512
南方客
南方客 2021-01-30 10:29

I would like to extract the information that is printed after a git status, which looks like:

# On branch master
# Your branch is ahead of \'origin/         


        
10条回答
  •  抹茶落季
    2021-01-30 11:28

    The top chunk of code in araqnid's answer doesn't work for me, so maybe something in git has changed since it was written 18 months ago. It works if I change:

    tracking_branch=refs/remotes/$remote/$remote_branch
    

    to

    tracking_branch=$remote/$remote_branch
    

    However there is still an issue when tracking a local branch, in which case you have to trim the remote part (which becomes '.'):

    tracking_branch=${tracking_branch#./}
    

    Then you can programmatically obtain the number of revisions behind and ahead as follows:

    set -- `git rev-list --left-right --count $tracking_branch...HEAD`
    behind="$1"
    ahead="$2"
    

    I've written scripts to do all that (and more - e.g. they can also attempt to spot remotes on the other side of a git-svn bridge), and published them in my git-config repository on github. For example, here's my git-compare-upstream. See the README for installation instructions and other handy related scripts.

提交回复
热议问题