Git’s rebase command can be puzzling for newcomers, and its description in the manpage doesn’t offer much clarity:
git-rebase – Forward-port local commits to the updated upstream head
Not exactly beginner-friendly, right? Thankfully, Travis Swicegood provides a more relatable metaphor:
Imagine a cleaver. Rebase acts like this cleaver, slicing and dicing commits however you see fit and placing them precisely where you want. You can essentially rewrite history with this command, reordering commits, merging them into larger ones, or even discarding them altogether.
Why is this useful? One common scenario is when you’re working on separate features or fixes in different branches. Instead of cluttering your master branch with numerous merge commits, you can consolidate your changes into a single cohesive commit using rebase. Another frequent use case is to incorporate changes from a project while keeping your modifications organized. Unlike merging, which can result in a tangled history, rebase maintains a cleaner and more logical order of commits.
Let’s walk through a simple example of using rebase. First, I’ll create a new branch for my feature and make some changes:
css
$ git checkout -b newfeature
Switched to a new branch "newfeature"
[.. made some changes, committed ..]
$ git checkout master
Switched to branch "master"
[.. made a change, committed ..]
At this point, our commit history looks like this:
[Insert screenshots of commit history]
Now, I want to incorporate the changes from the newfeature branch into the master branch. One option is to merge the branches with git merge newfeature. However, this creates a history that looks like this:
[Insert screenshot of merged history]
Alternatively, if we use git rebase newfeature, our commit history will appear like this:
[Insert screenshot of rebased history]
As you can see, the rebase approach results in a cleaner and more streamlined history. While this example demonstrates a straightforward scenario, future tips will delve into resolving merge conflicts, exploring different merging algorithms, and utilizing rebase’s interactive mode. This post serves as an introduction to the basics of rebase. If you have any clever rebase tricks, feel free to share them!