rebase vs merge
| merge | rebase | |
|---|---|---|
| History | Creates a merge commit; keeps the branch | Rewritten into a linear history |
| Conflict resolution | Once | Per commit |
| Public branches | Recommended | Do not use |
| Local work | Fine | Recommended |
Basic rebase
Bash
# Apply the latest main onto your feature branch
git checkout feature/my-feature
git rebase main
# If a conflict occurs
# 1. Edit files to resolve the conflict
# 2. git add the resolved files
# 3. git rebase --continue
# Abort and restore the original state
git rebase --abortinteractive rebase — cleaning up commits
Bash
# Edit the last 3 commits
git rebase -i HEAD~3Commands shown in the editor:
CODE
pick a1b2c3 first commit
pick d4e5f6 second commit
pick g7h8i9 third commitChange pick to one of the following:
| Command | Action |
|---|---|
pick | Keep as-is |
reword | Edit the commit message |
edit | Edit the commit contents |
squash | Fold into the previous commit (combine messages) |
fixup | Fold into the previous commit (discard this message) |
drop | Delete the commit |
squash example — cleaning up WIP commits
Bash
git rebase -i HEAD~4
# In the editor:
pick a1b2c3 feat: login feature
fixup d4e5f6 wip
fixup g7h8i9 wip 2
reword h0i1j2 fix: token refresh bugResult: 4 commits are cleaned up into 2.
cherry-pick — applying specific commits
Bash
# Find the commit hash
git log --oneline feature/hotfix
# Apply a single commit
git cherry-pick a1b2c3
# Apply a range
git cherry-pick a1b2c3..g7h8i9
# Stage only, without committing
git cherry-pick -n a1b2c3
# After resolving conflicts
git cherry-pick --continue
# Abort
git cherry-pick --abortPractical patterns
Bash
# Apply a hotfix to both main and the release branch
git checkout main
git cherry-pick fix-commit-hash
git checkout release/v2.0
git cherry-pick fix-commit-hash
# Clean up commits before opening a PR
git fetch origin
git rebase origin/main
git rebase -i origin/mainCaveats
- Never rebase commits that have already been pushed — it breaks collaborators' history
- If you must force-push, use
git push --force-with-lease(rejected if someone else pushed in the meantime)
Editorial note
AI tools may assist drafting. Check the evidence in each guide for whether commands were run and which environment was used. Confirm the current docs for your version before applying instructions, and email us about errors. email us
Topic-related official docs (auto-linked · not per-claim sources)Git documentation ↗
Questions & answers
Ask a question about this guide. We'll review and reply.