Skip to main content

This chapter of the explained series is a simple and mildly detailed explanation of git rebase . If you’ve had to rebase a git branch before you know how much of a pain and confusing it can get. I’ve been there a few times and thanks to my very helpful colleagues, I have a good enough understanding of it to not get frustrated anymore.

Before we get into it, here’s a summary git and some commands you should know.

Throughout this article, I’ll use two git branches for the explanations; a feature branch which is the branch you’re working on and a main branch which is the main branch with all the latest code.

Why would you need to rebase a branch

Rebase is integrating changes from one branch from another. Imagine you’re working on a feature branch and there’s another branch, main, that has all the changes from all developers in the team.

git checkout feature

git rebase main

Rebasing combines all the new commits in main to a single commit in the feature branch.

Here’s an example:

Imagine main has c1, c2, c3,  c4 and your feature branch has c1, c2, c3, c4; because you created it from the point where main just had c1 to c4. While you were working locally on your feature branch, your teammates updated pushed their work to main and now it has c1, c2, c3, c4, c7, c8. These new changes in the main branch are necessary for your feature branch .

Your branch looks like c1, c2, c3, c4, c,9 c10; c9 and c10 being the changes you created.

When you push your work to the main branch, you’d prefer it to just have your changes. git rebase will integrate all the changes in the main branch to your feature branch. All the changes/ commits that are in the main branch will be squashed into a single commit and you won’t end up having a ‘noisy’ commit history. So if there were 20 commits in the main branch that you needed in your feature branch, your commit history won’t have 21 commits but just 2.

 

Interactive rebase

The command to run an interactive rebase where you decide which changes/ commits you want to pick:

git rebase -i

This will open either a notepad or a vim editor I use the notepad because it just makes my life easier. The notepad/ vim editor will have a list of commits and some command with instructions at the bottom of the list; though the ones you’d most likely use are;

pick – picks a commit

drop – squashes a commit

Once you’ve indicated which commits you want to pick and drop, save the file and close it. The command will complete and you’ll have your changes in your branch.

Incase of an error or if you change your mind, undo the rebase with git rebase --abort.

For a much more detailed tutorial, try this.

Happy learning!!