How to Rebase in Git?

Shivam Chand
3 min readOct 24, 2020

As important Git is to a Developer, Rebase is to Git.

When you are working on a feature/branch and multiple people are also working on several other features/branches, it becomes difficult for one to keep track and merge all the branches to the master.

One of the most powerful feature available in Git is Rebase. When we rebase, all the commits are reapplied on the top of other base tip.

Rebase Feature

In the image above, the upper part shows the staging point at which you checked out to your branch from the master. In the master, after your checking out to branch; several other commits have been merged. In order to tackle the merge conflicts, you can do rebase(as shown in the later half of the image).

Merging(left), Rebasing(right)

This is an example of two different projects I worked on. In the first project(on the left), we were using merging while on the second project(on the right), we used rebasing.

Now I will share the commands to do the rebasing.

  1. Before working on any branch, always take a fresh pull from the remote
git pull origin master

2. Now create a new branch

git checkout -b <new-branch>

3. Take a rebase before working on the branch

git pull --rebase origin master

It will show that your branch is up-to-date.

Now make the changes.

4. After making all the changes, do the usual:

git add .
git commit -m "commit message"
git push origin <new-branch>

Pushing your changes to a remote branch ensures that your data won’t be lost in case of rebasing(rebasing can be tricky sometimes).

5. Now, rebase again just to ensure that nothing new has been merged to master since the last time you rebased.

git pull --rebase origin master

if multiple developers have not worked on the same modules as you had, then there will be no issues. It will show your branch is up-to-date. If not, then it will show all the merge conflicts in your code.

6. You can resolve those conflicts and then

git add .
git rebase --continue

Now your local branch is on the “same page” as that of the remote master.

7. Since you have multiple commits now after resolving the merge conflicts, next step is to “squash” the commits.

git rebase -i origin/master

Here you will see multiple commits, you have to push only the first commit and rest, you have to fixup, f. The commits marked ‘f’ will have their messages discarded in-favor of the previous commit’s message.

save and exit from that interface.

8. Now update the commit message if you want.

git commit --amend

9. Rebasing is done; now you have to force push your branch to remote

git push origin <new-branch> -f

That’s it. You have successfully rebased your code.

This was my first blog on Medium. Would love to hear the feedback on how to improve the blog.

--

--