Jim Fell
Jim Fell

Reputation: 14256

How to pragmatically check with bash script if a branch in git needs to be rebased?

I'm working on a bash script for my team to enforce regular rebasing of working branches. The problem I am facing at the moment is how to determine whether a branch is behind master and/or if it needs to be rebased, rather than blindly attempting to rebase the branch.

Here is a simplified version of what I have so far:

#Process each repo in the working directory.
for repo_dir in $(ls -1); do
    # if working branch is clean ...

        # BEGIN update of local master
        git checkout master
        git fetch origin
        git merge remotes/origin/master
        # END update of local master

        for sync_branch in $(git branch | cut -c 3-); do
            if [ "$sync_branch" != "master" ]; then
                # BEGIN rebase working branch
                git checkout $sync_branch
                git rebase master
                # Do NOT push working branch to remote.
                # END rebase working branch
            fi
        done
    fi
done

Any ideas would be much appreciated. Thanks!

Upvotes: 17

Views: 8450

Answers (1)

Schleis
Schleis

Reputation: 43690

To tell if you need to rebase your branch, you need to find out what the latest commit is and what was the last commit that your two branches share.

To find the latest commit on the branch:

git show-ref --heads -s <branch name>

Then to find the last commit that your branches have in common:

git merge-base <branch 1> <branch 2>

Now all you need to do is find out if these two commits are the same commit. If they are, then you don't need to rebase. If they are not, a rebase is required.

Example:

hash1=$(git show-ref --heads -s master)
hash2=$(git merge-base master foo/bar)
[ "${hash1}" = "${hash2}" ] && echo "OK" || echo "Rebase is required"

Though as stated in the comment, if you attempt to rebase a branch that is already up to date. Git will gracefully handle the situation and exit.

Upvotes: 41

Related Questions