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

Updated . Posted . Visible to the public. Repeats.

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"

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
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2012-07-24 11:38)