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

后端 未结 10 600
南方客
南方客 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:08

    In modern versions of git, @{u} points to the upstream of the current branch, if one is set.

    So to count how many commits you are behind the remote tracking branch:

    git rev-list HEAD..@{u} | wc -l
    

    And to see how far you are ahead of the remote, just switch the order:

    git rev-list @{u}..HEAD | wc -l
    

    For a more human-readable summary, you could ask for a log instead:

    git log --pretty=oneline @{u}..HEAD
    

    For my own purposes, I am working on a script that will replace @{u} with an appropriate guess, if no upstream is yet set. Unfortunately there is at this time no @{d} to represent the downstream (where you would push to).

提交回复
热议问题