How do I remove a file from the latest commit?
The easiest way to delete a file in your Git repository is to execute the “git rm” command and to specify the file to be deleted. Note that by using the “git rm” command, the file will also be deleted from the filesystem.
I think other answers here are wrong, because this is a question of moving the mistakenly committed files back to the staging area from the previous commit, without cancelling the changes done to them. This can be done like Paritosh Singh suggested:
git reset --soft HEAD^
or
git reset --soft HEAD~1
Then reset the unwanted files in order to leave them out from the commit (the old way):
git reset HEAD path/to/unwanted_file
Note, that since Git 2.23.0
one can (the new way):
git restore --staged path/to/unwanted_file
Now commit again, you can even re-use the same commit message:
git commit -c ORIG_HEAD
ATTENTION! If you only want to remove a file from your previous commit, and keep it on disk, read juzzlin's answer just above.
If this is your last commit and you want to completely delete the file from your local and the remote repository, you can:
git rm <file>
git commit --amend
The amend flag tells git to commit again, but "merge" (not in the sense of merging two branches) this commit with the last commit.
As stated in the comments, using git rm
here is like using the rm
command itself!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With