26

I was working on a branch and needed to get back on master for a quick fix so I committed my work in progress.

Now I am back in my branch and I would like to get back to the state where I haven't committed but all my changes are applied and ready to be committed (i.e. cancel the previous commit but my changes are not lost and they are shown in git status).

Amending the previous commit is not good enough for me as I want to see the changed files and lines (it makes it easier to work on my change).

I know git stash would have been a better solution but it's too late. I also tend to mix up (or loose) my stashed commits as they are not linked to a branch.

Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261
  • 2
    Do a soft reset of your branch: after checking it out, run `git reset --soft HEAD^`. That will make your branch point to the commit before the one that bothers you, without altering the index or working tree. – jub0bs Apr 09 '15 at 00:21

3 Answers3

38

There are basically two ways to solve this:

  1. Do a reset (on the master branch, or whatever branch the false commit is):

    git reset --soft HEAD~1
    

    The HEAD~1 is a relative address as explained here.

  2. Keep working and perform an amendment:

    git commit --amend
    

    In that case you pretend nothing happened, work further on your branch and call the command when you were planning to do a real commit. You kind of overwrite the last commit with all changes and (optionally) a new message.

And pro forma: it is indeed - as you mention yourself - better to perform a git stash, only saying for people that see this answer by accident and think the above is common practice (it is not).

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
10

From my understanding, you want to undo the latest commit to your branch while keeping all of the changes from the commit intact and staged.

You may want to try using the git reset command as listed below:

git reset --soft HEAD^

That should take your latest commit and undo it, while keeping all of the changes staged.

Christopher Wells
  • 1,918
  • 1
  • 15
  • 20
4

You should use git reset HEAD~1 (without --hard option)

It will do exactly what you want and HEAD~1 means here that you'd like to reset one commit, counting from the head (top) of the history.

This will not touch any files on the file system, so git will now see your edited files as changed but not committed.

  • Perhaps it is better to explicitly state `--soft`. I know it's very unlikely the default behavior will change, but if it does, some answers might be outdated. – Willem Van Onsem Apr 09 '15 at 00:25
  • Agree. But anyways, it hasn't been changed for a while, so it's likely to continue being safe to use it without ```--soft``` :) – Maxim Leonovich Apr 09 '15 at 00:29