Ayush Porwal

Deleting Last Two Commits and Re-syncing with Main

A guide on how to safely delete commits and re-sync your branch with the main branch using Git commands.

gitversion-controldevelopment

Introduction#

This morning, like any other work day, I logged into my GitHub account to check the status of my open pull requests. I noticed I had some merge conflicts and needed to sync with the main branch.

I found myself in a situation where I needed to delete the last two commits and re-sync with main. Here is how I solved it.

Step 1: Sync with Main#

First, I switched to the main branch and pulled the latest changes to ensure my local main was up to date.

git checkout main
git pull origin main

Step 2: Delete Commits#

Next, I switched back to my working branch. I needed to remove the last two commits. Git provides two primary ways to do this, depending on whether you want to keep your changes.

Option A: Soft Reset (Keep Changes)#

Use this if you want to undo the commits but keep the file changes in your staging area.

# This will keep changes in your working directory
git reset --soft HEAD~2

Option B: Hard Reset (Discard Changes)#

Use this if you want to completely discard the commits and the changes associated with them.

# This will delete changes permanently
git reset --hard HEAD~2

In my case, I didn’t require the changes from the last two commits, so I went with Option B.

Step 3: Sync and Push#

After resetting my branch, I synced it with main.

git merge main

Note: You can also use git rebase main, but I preferred a merge in this specific situation.

Finally, since I rewrote the git history by resetting commits, I needed to force push the changes to the remote repository.

The Safe Way to Force Push#

While you can use --force, it is safer to use --force-with-lease.

git push origin <current_branch> --force-with-lease
  • --force: Overwrites the remote history unconditionally.
  • --force-with-lease: Only overwrites if the remote branch hasn’t been updated by someone else since your last fetch. This prevents accidental overwrites of team members’ work.

I hope this guide helps if you ever find yourself in a similar situation!