267

By mistake, I did git add . and git commit in the develop branch. But luckily, I did not do git push.

So I wanted to revert it back to original state.

I tried git reset --soft and git reset HEAD --hard but looks like I have messed it up.

How do I fix this? I want to go back to original state and possibly keep the code changes.

blubb
  • 9,510
  • 3
  • 40
  • 82
chintan s
  • 6,170
  • 16
  • 53
  • 86

2 Answers2

578

I think you haven't messed up yet. Try:

git reset HEAD^

This will bring the dir to state before you've made the commit, HEAD^ means the parent of the current commit (the one you don't want anymore), while keeping changes from it (unstaged).

guessimtoolate
  • 8,372
  • 2
  • 18
  • 26
  • 9
    This might be a duplicate, but this is the over simplistic answer that I want 90% of the time. Thank you – geneorama Jun 14 '17 at 21:25
  • 1
    You, sir/ma'am, are a savior! – Amal Gupta Jul 28 '17 at 11:21
  • 5
    After you do this, if you want to completely remove the unstaged changes, you'll need to run the following: git reset --hard HEAD – nfriend21 Sep 20 '17 at 20:53
  • 6
    Don't know why this answer marked as correct. I get error thrown `fatal: ambiguous argument 'HEAD^': unknown revision or path not in the working tree. Use '--' to separate paths from revisions,` Doesn't work – Green Nov 05 '17 at 12:33
  • 1
    @Green same for me. I used this command instead to completely remove last commit: `git reset --hard HEAD~1` [Found here](https://www.git-tower.com/learn/git/faq/undo-last-commit) – Jose Nov 07 '17 at 05:12
  • 1
    if `fatal: ambiguous argument` simply use `git reset -- HEAD^` – Boop Nov 23 '17 at 19:16
  • 14
    On windows, the caret is a special character for CMD (it's used to escape a character, similar to the backslash in Linux) so you better quote "HEAD^". – bart Nov 24 '17 at 10:30
  • 95% of the time this works 100%... too bad I didn't find it a month ago! Simple, which is what I need. – alexwc_ Jul 22 '18 at 20:25
  • Question - and if i have done add . commit and the pull , i believe that this might effect on other files too and not only on mine? – MissSergeivna Jan 12 '21 at 10:51
135

Try simply to reset last commit using --soft flag

git reset --soft HEAD~1

Note :

For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • 3
    `fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree. Use '--' to separate paths from revisions` – Green Nov 05 '17 at 12:35
  • Try using git bash. If you're using Windows the console won't work for some reason, not sure why. Git bash does tho. – Fred Dec 08 '17 at 19:09
  • 4
    @Green Windows doesn't like `HEAD~1`, wrap it in quotes like `git reset --soft "HEAD~1"` – user56reinstatemonica8 Jan 25 '18 at 14:22