Reputation:
How can I remove a file from my last commit, but keep everything else? Please note that I haven't yet pushed anything to a remote repository, so I just have to do this locally.
My workflow:
untitled.txt
untitled.txt
fileThanks in advance!
Upvotes: 1
Views: 687
Reputation: 58578
The other answers are fine if you want to not only remove the file from the last commit, but completely.
But what if the creation of the file is not accidental, only the addition of that file to the commit?
If you want to just delete the file from the last commit, but keep the file in your working copy so that you can git add
it to another commit, you can add --cached
to the rm
command:
git rm --cached wanted-for-another-commit-but-not-this-one.txt
git commit -a --amend
Now verify that it's gone from the commit:
git show -p # no more diff between /dev/null and the file!
Verify it's still there:
ls -l wanted-for-another-commit-but-not-this-one.txt
Verify it's in the list of untracked files, eligible for a git add
:
git status
Basically what we have done is removed the file from the index of staged files, while keeping the working copy. The git commit -a --amend
command is aware not only of changes in the working copy, but in the index also. It notices a removal from the index and propagates that change to the newly rewritten commit.
Upvotes: 0
Reputation: 7426
Why not just make the very next commit delete the file? It is typically considered bad practice to edit a commit history, and there is no shame in just removing the file in a subsequent commit.
git rm untitled.txt
git commit -m "Woopsy"
Upvotes: 0
Reputation: 29539
You can easily change whatever you like in your last commit (messages, files, etc) with git commit --amend
.
So you would do something like this:
git rm untitled.txt
git commit --amend
Upvotes: 3