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^
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:
- remove the file
git rm <file>
- 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!
Existing answers are all talking about removing the unwanted files from the last commit.
If you want to remove unwanted files from an old commit (even pushed) and don’t want to create a new commit, which is unnecessary, because of the action:
- Find the commit that you want the file to conform to using ;
git log --graph --decorate --oneline
- Checkout that commit using
git checkout <commit_id> <path_to_file>
you can do this multiple times if you want to remove many files.
git commit -am "remove unwanted files"
Find the commit_id of the commit on which the files were added mistakenly, let’s say “35c23c2” here
git rebase 35c23c2~1 -i // notice: "~1" is necessary
This command opens the editor according to your settings. The default one is vim. If you want to change the global git editor, use;
git config --global core.editor <editor_name>
Move the last commit, which should be “remove unwanted files”, to the next line of the incorrect commit(“35c23c2” in our case), and set the command as
pick 35c23c2 the first commit fixup 0d78b28 remove unwanted files
You should be good after saving the file.
To finish :
git push -f
If you unfortunately get conflicts, you have to solve them manually.