Rebase
Git rebase is a powerful command that allows you to integrate changes from one branch into another by moving or rewriting commit history. It is an alternative to git merge, but instead of creating a merge commit, it rewrites the commit history to keep it linear.
Why Use Git Rebase?
-
Keeps commit history clean and linear: Instead of multiple merge commits, rebase makes it appear as if all work happened sequentially.
-
Avoids unnecessary merge commits: It moves your feature branch commits on top of the latest commit from the main branch.
-
Useful for integrating changes from remote branches: Before pushing changes, rebasing ensures your branch is up-to-date.
Example
Let's say you are working on a feature branch (feature-branch), and the main branch has received updates. Instead of merging, you decide to use rebase.
main:
A --- B --- C (main)
feature-branch:
\
D --- E (feature-branch)
A → B → Care the commits in themainbranch.D → Eare commits in thefeature-branch, which was created from B.
Now, suppose main has received new commits (C), and you want to update your feature-branch with these latest changes.
- Switch to
feature-branch. - Rebase your branch onto
main:git rebase mainWhat happens now:
- Git moves commits
DandEaside. - It updates
feature-branchwith the latest changes frommain(i.e., commitsC). - Then, it reapplies
DandEon top ofC.
- Handling Conflicts:
If there are conflicts, Git will pause the rebase and show a message:
To resolve, manually fix the conflict in the affected files, use
git addto stage teh resolved files. Continue the rebase:
git rebase --continue
- Successfully Rebased History
main:
A --- B --- C (main)
\
D' --- E' (feature-branch)
Now, D and E have been reapplied as D' and E' on top of C, keeping history linear.
Differences: Rebase vs Merge
| Feature | Merge | Rebase |
|---|---|---|
| Commit History | Creates a merge commit | Keeps history linear |
| Commit Order | Branches remain separate | Commits appear as if they were created sequentially |
| Use Case | Preserves original history | Makes history cleaner |
Commands
git rebase <branch>– Rebase your current branch onto another branch.git rebase --interactive <commit> (-i)– Start an interactive rebase for modifying commits.git rebase --continue– Continue rebase after resolving conflicts.git rebase --abort– Abort rebase and return to the original branch state.git rebase --skip– Skip the current conflicting commit and continue rebase.git rebase --onto <new-base> <old-base> <branch>– Rebase a branch onto a different base.git pull --rebase– Fetch changes and rebase instead of merging.