gitbranch

Determine whether two Git branches have diverged


I'd like to determine whether two Git branches have diverged or whether one of the branches could simply be fast forwarded to the other branch.

In other words, I want to check whether the current HEAD of one of the branches has been merged into the other branch at some point or if it contains commits that are not in the other branch.

Is there a way to do this without actually merging the two branches? A simple git diff does not help in this case.


Solution

  • I'm using this shell script snippet for that purpose:

    git_is_merged () {
        local revlist
        if revlist=$(git rev-list -1 "$1" --not "$2"); then
            if [ "$revlist" = "" ]; then
                echo "'$1' IS merged into '$2'."
            else
                echo "'$1' is NOT merged into '$2'."
            fi
        fi
    }
    
    alias gim='git_is_merged'
    

    Use it like gim origin/devel origin/master to determine whether origin/devel is merged into origin/master.

    Edit: For the sake of completeness, if you are working with named branches only, you could also use

    git branch --contains origin/devel | grep -q origin/master && echo "Merged" || echo "Not merged"
    

    or

    git branch --merged origin/master | grep -q origin/devel && echo "Merged" || echo "Not merged"
    

    for the same purpose.