How to amend the last commit to un-add a file

git

I have modified two files a, b in the last commit. But file b should not be commited, what's the workflow to amend this?

Best Answer

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.

Related Question