How to remove a file from the previous commit?

Written on by Sahil Bhatacharya in Mistakes Correction

There can be times when you would want to remove a specific file or part of the code from your last commit. To do it do the following:

git checkout HEAD^ myfile # this revert the file to the last commit.
git add myfile
git commit --amend --no-edit

In case you don't have a history or simply said: "it was a new file." You need to remove it from history altogether.

git rm --cached myfile
git commit --amend --no-edit

This is particularly useful when you have an open patch, and you have committed an unnecessary file, and need to force push to update the patch on a remote. The --no-edit option is used to keep the existing commit message.

Sign up below to receive updates, tips and more handy tutorials. It’s good stuff & I don’t spam.