Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readGit

Rebase stacked branches with --update-refs

Rebase the top of a branch stack with --update-refs to move branch tips that point into the rewritten commits.

You have three branches stacked on each other: api, then ui, then tests. Then main gets a hotfix. You rebase tests onto main, and api and ui stay behind on the old commits.

A plain git rebase main moves only the branch you are on. The branches underneath keep pointing at the commits you just replaced, so you check each one out and rebase it again, bottom first.

Rebase the top branch with --update-refs

Check out the top of the stack and pass --update-refs. Git rewrites the commits as usual, and any other branch that points at one of them is force-updated to the rewritten commit. I add -i so I can see what Git is about to do.

git switch tests
git rebase -i --update-refs main

Your editor opens with the todo list. Each branch in the stack got its own update-ref line:

pick 1ae3745 # add api
update-ref refs/heads/api
pick b4e1941 # add ui
update-ref refs/heads/ui
pick ae421f2 # add tests

Read it top to bottom. The update-ref lines record where api and ui should point once the rebase finishes. Save and close the editor without changes.

Git prints Updated the following refs with --update-refs and lists refs/heads/api and refs/heads/ui. The log shows one straight line with all three branches on it:

* 7f742f3 (HEAD -> tests) add tests
* d4659bf (ui) add ui
* 7de131a (api) add api
* 625f564 (main) hotfix on main
* 588ad47 base

Keep a branch where it is

The todo list is the control. Delete the update-ref refs/heads/ui line before you save and ui is left alone.

When I tried it, api moved onto main and tests was rebased. ui stayed on its old commit, with the old copy of "add api" underneath it.

Git also skips any branch that is checked out in another worktree. If a branch in your stack is open in a second working directory, rebase that one from there.

Turn it on for every rebase

If you work with stacked branches, set the config once:

git config --global rebase.updateRefs true

Git now behaves as if you had passed --update-refs on every rebase. With it set, I ran a plain git rebase main on ui in a two-branch stack, and api moved along with it. Pass --no-update-refs when you want the old behaviour for one run.

The option arrived in Git 2.38, so run git --version first if the flag is rejected.