How to Fix a Mistaken Commit Immediately?

How to Fix a Mistaken Commit Immediately?

The Problem

Note: If you are looking to delete a pushed commit, please refer to this solution How to Delete a Pushed Commit?. The following article is only a guide to deleting a "not" pushed commit, yet somehow it often appears in the top Google search results. Thank you!

A daily task for programmers is to write code, and by evening before leaving, we often ask each other, "Have you committed the code yet?". Or sometimes we hear a quirky joke like, "Even if the sky falls, don’t forget to commit the code before leaving." Because of someone’s urgent push, after committing, you realize there’s another file you forgot to add with the commit. It’s really frustrating, but should you add another commit just to push it up to remote?

Many people choose to create a new commit to correct the mistake, but that might be unnecessary because you may not know that an unpushed commit can still be fixed. So how do you fix the commit immediately?

Adding New Content to the Commit

Git allows us to change the last commit with the command git commit --amend --no-edit.

For example, right after committing, you realize you forgot to add README.md:

$ git add README.md  
$ git commit --amend --no-edit  

And that's it, the changes in README.md are now included in the last commit.

Removing Content from the Commit

Similarly, if you accidentally added a file, you can remove it using git reset HEAD^ path/to/file.

For example, right after committing, you realize you mistakenly added README.md to the commit and want to remove it:

$ git reset HEAD^ README.md  
$ git commit --amend --no-edit  

Changing the Commit Message

Git also allows you to change the message of the last commit with the command git commit --amend -m <message>.

$ git commit --amend -m "edited message"  

Soft Reset

This is a method when you want to roll back the last commit. That is, cancel the last commit but keep all changes in the staged state.

$ git reset --soft HEAD^  

This command cancels the last commit and returns all changes to staged, allowing you to start committing again from scratch.

Deleting an Unpushed Commit Without Reverting

This method applies to cases where you just committed locally and have not pushed to remote.

$ git reset --hard origin/branch  

With origin being the remote and branch being the working branch.

Note: A hard reset synchronizes the remote with the local. This means that whatever commits are on the remote will be brought down to local. All local commits that are not on the remote will be deleted. Be cautious when using this.

For example, if I just committed to develop and want to delete it:

$ git reset --hard origin/develop