How to amend the last commit to un-add a file?
Solution 1:
Update (couple of years later)
Jan Hudec
It's trivial to remove it from index only.
True: you can reset a file to its index content easily enough, as the more recent answer (written by Matt Connolly) suggests:
git reset HEAD^ path/to/file/to/revert
HEAD^
allows the file to access its content in the previous commit before the last one.
Then you can git commit --amend
, as I originally wrote below.
With Git 2.23 (August 2019), you might use the new git restore
command
git restore --source=HEAD^ --staged -- path/to/file/to/revert
shorter:
git restore -s@^ -S -- path/to/file/to/revert
Again, you then can git commit --amend
, as I originally wrote below.
Original answer (January 2011)
If this is your last commit (and you haven't pushed it anywhere), you can amend it:
(first stash or save b
)
git commit --amend
Then delete b, re-commit. Restore b and you're done.
--amend
Used to amend the tip of the current branch.
Prepare the tree object you would want to replace the latest commit as usual (this includes the usual -i/-o and explicit paths), and the commit log editor is seeded with the commit message from the tip of the current branch.
The commit you create replaces the current tip — if it was a merge, it will have the parents of the current tip as parents — so the current top commit is discarded.
Solution 2:
-
git diff --name-only HEAD^
- (optional) use to list the files that changed in the last commit. -
git reset HEAD^ path/to/file/to/revert
- to reset the index to that last version, leaving the working copy untouched. -
git commit --amend
- to amend that last commit to include the index changes
Solution 3:
Alternatively if you are using git gui
, you just select the "Amend last commit" option, the added file appears in the "Staged" list, click on it's icon to move it to the "Unstaged" list and commit.