How to rebase many branches (with the same base commit) at once?

I’m fairly sure that there isn’t a way to automatically do this. Remember that “git rebase master” can also drop you back to the shell needing you to resolve merge conflicts, so if you want to write a script to automate all this you need to take that into account.

You can fairly easily track which branches need updating, though. Hmm, for any branch, “git rev-list branch..master” will produce output if the branch is not up-to-date wrt (i.e. just commits on top of) master. So you need to loop through all the local heads except master to produce a report (nb “git show-branch” will approximately do this):

git for-each-ref 'refs/heads/*' | \
  while read rev type ref; do
    branch=$(expr "$ref" : 'refs/heads/\(.*\)' )
    revs=$(git rev-list $rev..master)
    if [ -n "$revs" ]; then
      echo $branch needs update
      git diff --summary --shortstat -M -C -C $rev master
    fi
  done

So if you were feeling brave, you could replace that “git diff” with something like “git checkout $branch && git rebase master” (or maybe just “git pull –rebase” if you’ve set that up). I think you’d then have to check for the existence of a “.git/rebase-apply” directory or check the index for unmerged files (“git ls-files -u”) to test if we’ve been left waiting to do a merge.

Of course, if there are no conflicts, then it’s easy… it’s producing something that also works when it’s not easy that’s the problem :p

And this doesn’t necessarily address what happens if one of your branches is based on something else… that’s why I mentioned using “git pull –rebase” instead, because that would rebase according to the branch configuration, not blindly from master. Although the detection isn’t based on the branch configuration… maybe it would be easiest just to check out each branch and do “git pull” and let the branch configuration handle everything, including whether to rebase or merge?

Leave a Comment