Git Rebase

Rebase is another way to bring the changes of one branch into another. Merge keeps the true history with a merge commit. Rebase takes your commits and replays them on top of the other branch, so the history becomes a straight line.

Syntax

git rebase <branch>
git rebase --continue
git rebase --abort
git rebase -i HEAD~3

Example: rebase a feature branch on main

The branch feature has 2 commits, and main got one new commit after the split. Let us see the history before the rebase.

Terminal output

$ git log –oneline –graph –all
* 42d4ffb (HEAD -> main) Add license
| * 1abd892 (feature) Add chapter 2
| * 0025648 Add chapter 1
|/
* d0a7a31 Add intro

Terminal output

$ git switch feature
Switched to branch 'feature'
$ git rebase main
Rebasing (1/2)
Rebasing (2/2)
Successfully rebased and updated refs/heads/feature.
$ git log –oneline –graph –all
* b0bb39f (HEAD -> feature) Add chapter 2
* 4044354 Add chapter 1
* 42d4ffb (main) Add license
* d0a7a31 Add intro

Now the two commits of feature are on top of main, in a straight line. Look at the hashes: the commits “Add chapter 1” and “Add chapter 2” have new hashes, because they are new commits with a new parent.

To finish, move main forward with a fast-forward merge. There is no merge commit now.

Terminal output

$ git switch main
Switched to branch 'main'
$ git merge feature
Updating 42d4ffb..b0bb39f
Fast-forward
ch1.txt | 1 +
ch2.txt | 1 +
2 files changed, 2 insertions(+)
create mode 100644 ch1.txt
create mode 100644 ch2.txt

Merge vs Rebase

TopicMergeRebase
HistoryKeeps the real history, has merge commitsStraight, clean line
CommitsNot changedRe-created with new hashes
Safe on shared branchesYesNo
ConflictsSolved one time in the merge commitMay need to be solved for each commit

The golden rule of rebase

Never rebase commits which you have pushed and others are using. Rebase rewrites the commits, so other people will have the old commits and Git will be confused for them. Rebase only your own local branches.

If there is a conflict during the rebase

Git stops at the commit with the conflict. Fix the files, then:

git add <file>
git rebase --continue

If it becomes too difficult, go back to the starting point with git rebase --abort.

Interactive rebase

The option -i opens a list of your last commits, where you can reorder, edit, drop or join (squash) them before sharing the branch.

git rebase -i HEAD~3
pick 1a2b3c4 Add chapter 1
squash 5d6e7f8 Fix typo in chapter 1
reword 9a8b7c6 Add chapter 2

In this list, the second commit is joined into the first one, and the third message can be changed.

Note: A common team habit: rebase your own feature branch on the latest main before opening a pull request. Then merge it with a normal merge or squash. Next: Git Stash.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.