How do I remove a modified file from the git index and discard the modifications in a single step?

StackOverflow https://stackoverflow.com/questions/17891521

  •  04-06-2022
  •  | 
  •  

Question

I recently performed a sloppy big commit to the wrong branch. I decided that I wanted the changes committed to be on a different branch and to possibly split the big commit into several smaller commits. I performed a git cherry-pick -n as indicated by this answer. This resulted in a bunch of staged changes in my current branch. I knew I wasn't going to need one of those changes. So I wondered: Is there any way to remove a modified file from the index and LOSE the changes in a single step? Most of the solutions I've seen require a git reset followed by a git checkout -- path/to/file.

Was it helpful?

Solution

What I ended up doing was a git checkout HEAD -- path/to/file which, as I understand it, replaced the file with the one from the HEAD commit's tree, rather than checking in the index first.

I came up with this solution without consulting the git man pages, but thanks to @torek for pointing out the git-checkout(1) man page. It was the fifth form of git checkout that I used, which looks like this:

git checkout [-p|--patch] [<tree-ish>] [--] <pathspec>...

Part of the documentation for that form says:

The <tree-ish> argument can be used to specify a specific tree-ish (i.e. commit,
tag or tree) to update the index for the given paths before updating the working
tree.

So what actually happened was this: git replaced the file in the index with the version from HEAD (effectively removing the file from the index), then replaced the file in the working tree with the version from the index, eliminating the changes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top