Git’s rebase command reapplies your changes onto another branch. As opposed to merging, which pulls the differences from the other branch into yours, rebasing switches your branch’s base to the other branch’s position and walks through your commits one by one to apply them again.
Let’s look at an example. While working on a branch named
login, based on the
master branch, one of your team members pushed some changes to
master. You need these changes to finish the login feature in your branch.
master branch back into yours would result in a merge commit, which includes the changes between both branches and exists to show where a merge occured. We won’t need to know when we merged the
master into the
login branch in the future. Instead, we’d like to pretend that all commits on the
login branch happened based on the new state of the
Git’s rebase command temporarily rewinds the commits on your current branch, pulls in the commits from the other branch and reapplies the rewinded commits back on top. By switching the current This bases the current branch onto the other branch.
$ git rebase master First, rewinding head to replay your work on top of it... Fast-forwarded login to master.
It’s as if you didn’t start working in the
login branch before the
commits you pulled in were made. You can also
rebase so you don’t have to switch out of your current branch.
Conflicts served in smaller chunks
Besides keeping your history clean, rebase also has your back when you run into a merge conflict during the rebase:
$ git rebase master First, rewinding head to replay your work on top of it... Applying: login Using index info to reconstruct a base tree... Falling back to patching base and 3-way merge... Auto-merging config/environment.rb CONFLICT (content): Merge conflict in config/environment.rb Failed to merge in the changes. Patch failed at 0001 login When you have resolved this problem run "git rebase --continue". If you would prefer to skip this patch, instead run "git rebase --skip". To restore the original branch and stop rebasing run "git rebase --abort".
Because rebase merges every commit individually, conflicts will be served in
smaller chunks making them easier to fix and understand. When you’re done
fixing a conflict, simply
git add the file and continue rebasing:
$ git rebase --continue
Rebase vs Merge
When you’re working on a feature branch and you need changes from the main master branch, I would suggest using rebase. Merge can be used when you want to merge a feature branch back into your master branch. That way, you’ll be able to see when you merged in what in the future because you have that merge commit I called “nasty” before. It isn’t, really.
What I would like to ask you is to rebase your feature branch to the main master branch before merging it in. This way you make sure your branch applies cleanly to the branch you’re merging into.