How to Rebase Branch in Git: Simple Guide
To rebase a branch in Git, use the command
git rebase target-branch while on your feature branch. This moves your branch's commits on top of the latest commits from the target branch, creating a cleaner history.Syntax
The basic syntax to rebase a branch in Git is:
git checkout feature-branch: Switch to the branch you want to rebase.git rebase target-branch: Reapply your branch commits on top oftarget-branch.
This updates your feature branch to include the latest changes from the target branch.
bash
git checkout feature-branch git rebase target-branch
Example
This example shows rebasing a feature branch named feature onto the main branch to update it with the latest changes.
bash
git checkout feature git rebase main
Output
First, rewinding head to replay your work on top of it...
Applying: Add new feature implementation
Common Pitfalls
Common mistakes when rebasing include:
- Rebasing a branch that is shared with others, which can cause conflicts and confusion.
- Not resolving conflicts properly during rebase, which pauses the process.
- Using
git rebaseinstead ofgit mergewhen you want to preserve history.
Always communicate with your team before rebasing shared branches.
bash
git checkout feature # Wrong: rebasing a public branch without coordination # git rebase main # Right: coordinate or use merge if unsure # git merge main
Quick Reference
| Command | Description |
|---|---|
| git checkout feature-branch | Switch to your feature branch |
| git rebase target-branch | Move your commits on top of target branch |
| git rebase --continue | Continue rebase after resolving conflicts |
| git rebase --abort | Cancel rebase and return to original state |
| git status | Check current rebase status and conflicts |
Key Takeaways
Use
git rebase target-branch on your feature branch to update it cleanly.Always resolve conflicts carefully during a rebase using
git rebase --continue.Avoid rebasing branches shared with others without coordination to prevent issues.
Use
git rebase --abort to cancel a problematic rebase safely.Rebasing creates a linear history by moving your commits on top of the target branch.