Read more

Git: How to rebase your feature branch from one branch to another

Arne Hartherz
July 24, 2012Software engineer at makandra GmbH

In a nutshell: Use git rebase --onto target-branch source-commit

  • target-branch means "branch you want to be based on"
  • source-commit means "commit before your first feature commit"

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

Let's say my-feature-branch is based on master and we want it to be based on production. Consider this history:

%%{init: { 'gitGraph': {'showCommitLabel': true, 'mainBranchName': 'production'}} }%%

gitGraph
  commit id: "1"
  commit id: "2"
  branch master
  commit id: "3"
  commit id: "4"
  branch my-feature-branch
  commit id: "5"
  commit id: "6"

Here, master has commits that are not yet in production (number 3 and 4).

Just doing a simple git rebase production from my-feature-branch will do nothing, as production is already in its history. Merging the feature branch into production would now merge commits 3 through 6, including commit 3 and 4 from master.

%%{init: { 'gitGraph': {'showCommitLabel': true, 'mainBranchName': 'production'}} }%%

gitGraph
  commit id: "1"
  commit id: "2"
  branch master
  commit id: "3"
  commit id: "4"
  checkout production
  merge master
  commit id: "5"
  commit id: "6"

This is not what we want.

Instead, we want to chop off our commits since master (number 5 and 6) and place them on production. We need to do this (while being in my-feature-branch):

git rebase master --onto production

This tells git you are moving the commits since master to production, and you'd end up with this:

%%{init: { 'gitGraph': {'showCommitLabel': true, 'mainBranchName': 'production'}} }%%

gitGraph
  commit id: "1"
  commit id: "2"
  branch master
  commit id: "3"
  commit id: "4"
  checkout production
  branch my-feature-branch
  commit id: "5"
  commit id: "6"

Note that after doing that, you will have changed your branch's history and need to do a forced push, if it was on origin before.


As always, you can supply commit hashes, not just branch names (which are only shortcuts to a commit anyway).

See also

Arne Hartherz
July 24, 2012Software engineer at makandra GmbH
Posted by Arne Hartherz to makandra dev (2012-07-24 13:38)