fb-pixel

How to Delete a Commit in Git

Want to delete a Git commit? Learn the safe and correct ways to undo mistakes in your project history.

Git refers to the most potent version control system for applications that developers use as a way of tracing and handling the alterations of the code. However, there might be cases when you might need to remove a commit: a mistake, sensitive information added accidentally, or to clean up your history in general.

1. Delete the Most Recent Commit (Before Push)

If you have not pushed your commit to the remote repository yet

git reset --soft HEAD~1
  • It will remove the last commit, but keep your changes in staging.
  • Use --mixed to unstage changes or --hard to delete them completely.
git reset --mixed HEAD~1   # unstages changes
git reset --hard HEAD~1 # deletes changes completely

2. Delete a Specific Commit (Unpushed)

If the commit is not the latest one, use interactive rebase:

git rebase -i HEAD~N

Replace N with the number of previous commits you want to view (e.g., HEAD~4).

  • A list will open in your default editor.
  • Change pick to drop in front of the commit you want to remove.
  • Save and close the editor.

Done. The unwanted commit will be deleted.

3. Delete Commit After Push

If you have already pushed the commit and want to delete it:

Step 1: Reset to the previous commit

git reset --hard HEAD~1

Step 2: Force push the change

git push origin main --force

4. Delete Local Commits Without Touching Remote

If you want to delete commits only from your local branch:

git reset --hard origin/main

It will reset your local branch to match the latest state of the remote.

5. Use Git Reflog to Restore Mistakenly Deleted Commits

If you want to restore mistakenly deleted commits.

git reflog

Find the commit hash and restore it using:

git checkout <commit-hash>

Or:

git reset --hard <commit-hash>

Conclusion

It is simple to erase commits in Git, but one has to be responsible about it. Make sure that your commit is pushed before making the choice of approach. Use –soft, –mixed or –hard according to your relative degree of wanting to retain. And note that Git is strong, but only when used with great care.

Related Posts

Ali Rehman

Rehman is focusing on delivering easy-to-follow tutorials related to social media, technology, and daily life hacks. With a passion for simplifying digital tasks, he provides practical guides that help readers enhance their social media presence and tackle everyday challenges with ease.
Back to top button
>
Join Now