Git rebase onto

on Christopher Hoelter's Blog

How to do a controlled git rebase.
#programming

Git rebase is a nice way to move a grouping of commits. The default behavior is not always desirable, moving all commits after the common ancestor point between two branches.

git rebase --onto gives you the option to specify exactly where and what commits you want to move. The full command looks like git rebase <target branch> <commit hash on current branch that's before all the commits you want to move>.

For sake of example, let's say you have a branch checked out called feature-1 and you want to move your feature commits onto the latest changes in main.

Your branches look like this:

A   B   C   D   E
o---o---o---o---o  main
         \
          \AA  BB  CC  DD  EE
           o---o---o---o---o  feature-1

And you want them to look like this:

A   B   C   D   E
o---o---o---o---o  main
                 \
                  \AA  BB  CC  DD  EE
                   o---o---o---o---o  feature-1

To accomplish this, you would follow these steps.

  1. git fetch to update origin/main
  2. git checkout feature-1 to ensure the feature branch is checked out
  3. git rebase --onto origin/main C to move all your current commits after commit C onto the head of origin/main.

That's it! There are all sorts of useful things you can do with a controlled rebase specifying the exact commit you want to use.


Please leave a comment or drop a message at https://lists.sr.ht/~hoelter/public-inbox. Email me directly at blog@christopherhoelter.com.