Understanding Git Rebase Basics

What about git merge?

Some Examples

Before we start…

SCENARIO 1 :: My feature is several commits behind master. I want to update my feature branch with the latest changes on master.

What I have…
What I want!

SCENARIO 2 :: My feature was branched from another feature branch. I want to change this so my feature starts from master branch instead.

Rebase Preparation (master)

  • run git checkout master
  • run git pull to get the latest changes from remote
  • run npm test to ensure tests are passing.
  • If yours tests are failing here on master, it’s advised to resolve these issues before you rebase feature onto master.

Rebase Preparation (feature)

  • run git checkout feature
  • run git pull to get the latest changes from remote

Find the common ancestor with master using git-merge-base

  • run git checkout feature
  • run git merge-base master feature to find the most recent commit both branches have in common.
  • This will generate a long commit ID string looking something like this: abcdef1234567890abcdef.

Run git-rebase

  • NOTE: If you run into any issues, you can run git rebase --abort to cancel the entire process. Rebasing can be instantaneous when no conflicts are found, but if you’re rebasing a feature branch that is missing tens/hundreds or commits from master, expect a long process of fixing conflicts.
  • run git rebase --onto master abcdef1234567890abcdef. Replace the long ID string with the ID string generated on your end.
  • If conflicts are found, resolve any files and run git add . when done to stage the changes. Then run git rebase --continue to continue the process.
  • Eventually the process will complete, and your feature branch will now contain a clean record with all of the latest from master.
  • If your pre-rebased branch was pushed to upstream, you’ll need to run git push --force to overwrite the pre-rebased branch with your new clean rebased branch.

Conclusion

References

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store