How to Safely Delete the Last Commit from Git

When working with Git, it’s common to run into mistakes — maybe you committed sensitive data, added the wrong files, or realized the last commit simply doesn’t belong. Fortunately, Git provides straightforward ways to remove the most recent commit from both your local repository and the remote branch.

Note: This approach is best used when you’re working alone on a branch. If teammates are also using it, force-pushing can overwrite their work.

Step 1. Switch to the Correct Branch

If you’re not already on the branch where the unwanted commit exists, switch to it:

git checkout <branch-name>

Step 2. Reset to the Previous Commit

Find the commit hash just before the one you want to delete and reset to it:

git reset --hard <commit-hash>

This removes the unwanted commit and resets your branch history to the specified commit.

Step 3. Push the Changes to Remote

Now push the updated branch to the remote repository. Since this rewrites history, you’ll need to force the push:

git push --force

Warning: --force rewrites history on the remote branch. Use it carefully.

Finally, your commit gets removed from your remote and local branches.