Removing Git Commits

How to remove commits in Git?

Using git reset --hard will DELETE any changes in your working directory. Ensure you stash any local changes you want to preserve before running this command.

If you are on the commit you want to modify, you can use the following command to remove it:


git reset --hard HEAD~1

Here, HEAD~1 refers to the commit immediately before the current HEAD.

Alternatively, you can use git log to find the commit ID of the commit you want to revert to, and then run:


git reset --hard <sha1-commit-id>

If you have already pushed the commit to a remote repository, you will need to force push to remove it:


git push origin HEAD --force

However, if others have already pulled the commit, it’s better to create a new branch. Otherwise, when they pull again, it will merge the changes back into their work and get pushed up again.

In such cases, it might be preferable to use git revert to create a “mirror image” commit that undoes the changes. Both commits will still appear in the log, but the changes will be negated.

With over 10 years of experience in version control systems, I’ve found another option that works well, which is:


git rebase -i <commit>~1

This command initiates an interactive rebase starting just before the commit you want to remove. Your text editor will open, listing all commits from that point onwards. Simply delete the line containing the commit you want to eliminate and save the file. The rebase process will then delete that specific commit and replay the remaining commits back into the log.

Interactive rebase is especially powerful because it allows you to rewrite commit history, and it’s great for cleaning up messy commit sequences.

In my experience, which includes dealing with various scenarios in Git, it’s crucial to consider situations where you might not want to lose all your work due to a mistake.

If you want to keep your work and simply ‘undo’ the commit (before pushing to the repository), use:


git reset --soft HEAD~1

Avoid using the --hard flag unless you intend to discard your work in progress since the last commit. The --soft flag allows you to keep your changes in your working directory, making it easy to amend or recommit as needed.

This method is ideal when you realize you’ve made a mistake but want to retain your changes to refine them before committing again.