0
0
GitHow-ToBeginner · 3 min read

How to Drop a Commit Using Git Rebase

To drop a commit using git rebase -i, start an interactive rebase with git rebase -i HEAD~N where N is the number of commits to review. In the editor, delete the line with the commit you want to drop, save, and close to apply the change.
📐

Syntax

The basic syntax to drop a commit using interactive rebase is:

  • git rebase -i HEAD~N: Starts an interactive rebase for the last N commits.
  • In the editor, each commit is listed with a command like pick.
  • To drop a commit, delete its line or replace pick with drop.
  • Save and close the editor to apply the rebase.
bash
git rebase -i HEAD~N
💻

Example

This example shows how to drop the second most recent commit from the last 3 commits.

bash
# Start interactive rebase for last 3 commits
git rebase -i HEAD~3

# Editor opens with lines like:
# pick abc123 Commit message 1
# pick def456 Commit message 2
# pick ghi789 Commit message 3

# To drop the second commit, delete or change the line:
# pick def456 Commit message 2

# Save and close the editor

# Git applies the rebase without the dropped commit
Output
Successfully rebased and updated refs/heads/main.
⚠️

Common Pitfalls

  • Not specifying enough commits: If you use HEAD~2 but the commit to drop is older, it won't appear in the list.
  • Conflicts during rebase: Dropping commits can cause conflicts; resolve them and continue with git rebase --continue.
  • Dropping commits on shared branches: Avoid dropping commits on branches others use to prevent history conflicts.
  • Forgetting to save the editor: Changes won't apply if you close without saving.
bash
## Wrong way: Trying to drop a commit not in the last N commits
# git rebase -i HEAD~2  # commit to drop is older than 2 commits

## Right way: Increase N to include the commit
# git rebase -i HEAD~5
📊

Quick Reference

CommandDescription
git rebase -i HEAD~NStart interactive rebase for last N commits
pickKeep the commit as is
dropRemove the commit from history
git rebase --continueContinue rebase after resolving conflicts
git rebase --abortCancel the rebase and restore original state

Key Takeaways

Use git rebase -i HEAD~N to start interactive rebase including the commit to drop.
Delete the commit line or replace pick with drop in the editor to remove it.
Resolve any conflicts during rebase and use git rebase --continue to proceed.
Avoid dropping commits on branches shared with others to prevent history conflicts.
Always save and close the editor to apply your changes.