How to remove or modify files in the Git commit

It happens to every Developer while committing their code, by mistake they commit some unwanted files or code. Instead of creating a new commit, we can fix this mistake in the same commit.

Use the below command to change the position of HEAD of your branch.

git reset --soft HEAD^

or

git reset --soft HEAD~1

Change the number ~1, based on your requirement.

  • 1 = uncommit the previous commit
  • 2 = uncommit the last two commits and so on

If you want to modify the content of the file. Edit the file directly. Alternatively, if you want to remove the file from the commit then use the below command.

git reset HEAD path/to/unwanted_file

Now commit again, you can even re-use the same commit message or make an update to the existing commit message.

git commit -c ORIG_HEAD

PS: This is only possible if the changes are not pushed to the remote repository and present in the local repository. Otherwise, the remote repository will show a different commit for the changes.