Jim Fell Jim Fell - 1 year ago 92
Git Question

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

Any ideas would be much appreciated. Thanks!

Answer Source

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.


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download