Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove files from Git commit

Tags:

git

git-commit

How do I remove a file from the latest commit?

like image 581
Lolly Avatar asked Sep 18 '12 16:09

Lolly


People also ask

How do I remove files from a git commit remote?

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.


2 Answers

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  
like image 110
juzzlin Avatar answered Oct 21 '22 17:10

juzzlin


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:

  1. remove the file git rm <file>
  2. commit with amend flag: 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!

like image 390
CharlesB Avatar answered Oct 21 '22 16:10

CharlesB