简体   繁体   中英

List branches not merged to their upstream

I'd like a command similar to git branch that will list all local branches that are not merged with their upstream.

This is something git branch knows about, as git branch -d <branch-name> will fail for branches that are not merged.

Are you looking for this:

git branch --no-merged

Above command will list out all the branches which are not merged to your current branch. if you need to check for other branch then

git branch --no-merged master

You can also compare upstream branches by specifying the -r flag and a ref to check against, which can be local or remote:

git branch -r --no-merged origin/master

As far as I know, there is no single built-in Git command to list all local branches that are behind their upstream branch (if any). However, you can implement the desired functionality using existing Git commands. See below.

Script

#!/bin/sh

# git-bbu.sh
#
# List the local Branches Behind their Upstream branch, if any.
#
# Usage: git bbu
#
# To make a Git alias called 'bbu' out of this script,
# put the latter on your search path, and run
#
#   git config --global alias.bbu \
#       '!sh git-bbu.sh'

if [ $# -ne 0 ]; then
    printf "%s\n\n" "usage: git bbu"
    exit 1
fi

git for-each-ref --format='%(refname:short)' refs/heads | \
    while read ref; do
      if (git rev-parse --verify --quiet "$ref"@{upstream} &&
          ! git diff --quiet "$ref"..."$ref"@{upstream}) \
              >/dev/null 2>&1; then
        printf "%s\n" "$ref"
      fi
    done

Explanation

Run

git for-each-ref --format='%(refname:short)' refs/heads

to list all local branches (Why not just use git branch , here? Because, in a script, you should try to use plumbing Git commands instead of porcelain ones). Pipe it to a while loop, and, for each such local branch,

  • Check whether the local branch has an upstream branch, using

     git rev-parse --verify --quiet "$ref"@{upstream} 
  • Check whether the local branch is behind its upstream branch, using (the logical negation of)

     git diff --quiet "$ref"..."$ref"@{upstream} 

If both conditions are verified, print the name of the branch.

References

git for-each-ref has an "upstream" field, which can show if the branch is up-to-date with its upstream. You can then filter its output to show only those which are ahead of their upstreams:

$ git for-each-ref --format='%(upstream:trackshort)..%(refname:short)' | awk -F '\\.\\.' '$1~/>/{print $2}'

this skips branches which do not have upstreams, modify the filter if it's not what you need (the $1 is empty then in the awk record). ".." is used aa separator because you cannot have the sequence in reference name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM