-1

The typical question is how to remove the latest commit. This is easy: git reset --hard HEAD~1

But ... I don't want the working directory to be overwritten with the new head contents.

If you reset the head, the working directory is restored to the contents of the repo as of that head commit. I want to keep my changed files.

E.g. I have changed three files, but want to commit only two. I accidentally commit all three. If I reset the head, not only is the bad commit removed, but all of the changed files are reverted. I want to remove the latest commit, then commit just the two I intended to commit. This means that I need to keep the changed files in the working directory.

I think I've explained the issue well enough. Or at least I hope so.

  • 2
    Use soft or mixed reset, depending on what you want to happen to Git's index (aka the staging area). See Tim Beigeleisen's answer for the `--soft` variant. With `--mixed` / the default, you'll have to `git add` files again, rather than resetting/restoring one file. – torek Dec 07 '21 at 04:09

1 Answers1

2

Perhaps a soft reset would work for you here:

git reset --soft HEAD~1

This will move the HEAD pointer back one commit, to the second to last commit. It will also stage the changes for the three files you modified. You may unstage the changes to the third file which you don't intend to commit, and then make another commit:

git commit -m 'modified only two files'

Now your branch will have a new commit containing only the changes to the two files which you intended.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360