Skip to content

Instantly share code, notes, and snippets.

@silvioramalho
Created April 17, 2025 19:20
Show Gist options
  • Save silvioramalho/03f2f06a969f8a942f569500afdf350a to your computer and use it in GitHub Desktop.
Save silvioramalho/03f2f06a969f8a942f569500afdf350a to your computer and use it in GitHub Desktop.
Remove Last Two Commits in Git

Remove Last Two Commits in Git

This guide explains how to remove the last two commits from your branch and restore the state to the third commit from the end (keeping your working tree clean and history intact).

Scenario

  • You're on a feature branch (e.g., feature/add-auth) based on main
  • You've made 4 commits
  • You want to remove the last 2 commits, keeping the state from the third last commit

Step-by-step

1. Checkout your feature branch

git checkout feature/add-auth

2. Reset the branch to the third last commit

Option A: Discard commits and working directory changes

git reset --hard HEAD~2

This removes the last two commits and resets your working directory to the state of the third commit from the end.

Option B: Discard commits but keep changes staged

git reset --soft HEAD~2

Keeps all changes in the staging area, allowing you to re-commit.

Option C: Discard commits but keep changes in working directory (unstaged)

git reset --mixed HEAD~2

Useful if you want to selectively add files again before committing.


3. Force push to update the remote branch

git push --force

Result

Your branch feature/add-auth will be set back to the state of the third last commit, and the last two commits will be removed from history.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment