0
0
GitHow-ToBeginner · 4 min read

How to Use Git Rebase: Simple Guide and Examples

Use git rebase to move or combine commits from one branch onto another, creating a cleaner project history. Run git rebase branch-name to replay your current branch commits on top of branch-name. Resolve any conflicts, then continue with git rebase --continue.
📐

Syntax

The basic syntax of git rebase is:

  • git rebase <base-branch>: Replays your current branch commits on top of base-branch.
  • git rebase --continue: Continues the rebase after resolving conflicts.
  • git rebase --abort: Cancels the rebase and returns to the original state.
bash
git rebase <base-branch>
git rebase --continue
git rebase --abort
💻

Example

This example shows how to update your feature branch with the latest changes from the main branch using git rebase. It replays your feature commits on top of the updated main branch.

bash
git checkout feature
# Make some commits on feature branch
# Now update feature branch with main branch changes

git fetch origin
git rebase origin/main

# If conflicts occur, fix them, then:
git add <fixed-files>
git rebase --continue

# After successful rebase, push with force to update remote

git push --force-with-lease
Output
First, git applies your commits on top of origin/main. If conflicts happen, git pauses and asks you to fix them. After fixing, 'git rebase --continue' resumes the process. Finally, your feature branch history is rewritten as if based on the latest main.
⚠️

Common Pitfalls

Common mistakes when using git rebase include:

  • Rebasing public branches that others use, which can cause confusion and conflicts.
  • Forgetting to resolve conflicts properly before continuing the rebase.
  • Not using git push --force-with-lease after rebasing a remote branch, which can overwrite others' work.

Always communicate with your team before rebasing shared branches.

bash
## Wrong: Rebasing a shared branch and pushing normally

git rebase main
git push origin feature

## Right: Use force-with-lease to safely update remote

git rebase main
git push --force-with-lease origin feature
📊

Quick Reference

CommandDescription
git rebase Replay current branch commits on top of
git rebase --continueContinue rebase after resolving conflicts
git rebase --abortCancel rebase and restore original state
git push --force-with-leaseSafely update remote branch after rebase

Key Takeaways

Use git rebase to create a clean, linear commit history by moving your commits onto another branch.
Always resolve conflicts carefully and continue the rebase with git rebase --continue.
Avoid rebasing branches shared with others unless you coordinate to prevent conflicts.
After rebasing a remote branch, use git push --force-with-lease to safely update it.
Use git rebase --abort to cancel if you encounter problems during rebase.