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

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

    git status has a --porcelain option that is intended for parsing by scripts. It is based on the --short output - they are almost identical at the time of writing (see the "Porcelain Format" section of the git status man page for details). The main difference is that --short has colour output.

    By default no branch information is shown, but if you add the --branch option you will get output like:

    git status --short --branch
    ## master...origin/master [ahead 1]
    ?? untrackedfile.txt
    ...
    

    If you are up to date (after a fetch), the branch line will just be:

    ## master
    

    If you are ahead:

    ## master...origin/master [ahead 1]
    

    If you are behind:

    ## master...origin/master [behind 58]
    

    And for both:

    ## master...origin/master [ahead 1, behind 58]
    

    Note that git status --porcelain --branch is only available in 1.7.10.3 or later (though git status --short --branch has been available since 1.7.2 ).

提交回复
热议问题