How to recover the previous commit?

Asked

Viewed 10,940 times

16

After you have added modified file and have given commit, I had to modify the whole structure of the code, but it didn’t work and I wanted to have access to the previous code again.

How do I retrieve the contents of commit previous?

  • I recommend putting in the .gitconfig the following: undo = reset HEAD~1 --mixed

3 answers

16


You can use the following command:

git reset HEAD~1

This will return to the last commit, but leaving the changes in the file in status unstaged. If you want to delete the changes, the command is:

git reset --hard HEAD~1
  • 1

    But you can see the code I typed before the commit?

  • Like I said, without the --hard it will keep the changes in the file, only that unstaged, if you use the option, then it goes back to the state of the file that was in the commit.

6

To undo the last commit you can do:

$ git reset --soft HEAD^

That way you’ll lose the commit but keep all the code you had "commited" and the current state, before resetting.

If you want to see what was done in the last commit(s) you can do:

$ git log -p -2

So you see the hash and changes of the last two commits.

You can also jump into a new branch $ git checkout -b novo-ramo and checkout that specific commit:

$ git checkout 12345678901234567890123456789012345678ab

2

The steps I usually take for a put code in a certain state of development are:

  1. List the commits effected:

    git log
    
  2. Identify which the commit I’m interested in replenishing through your hash, for example:

    Commit: 54eb79a5590d1716b9ac335457230d771181f4a7
    
    Author: Lahan
    
    Date:   Tue Dec 23 23:36:01 2014 +0100
    
    Message: Added 'mobile' field to user table in profiler app
    
  3. Effect a reset, noting the hash of commit which I intend to be the new state of the code:

    git reset --hard 54eb79a
    

Now all the code is in the state it was in after the commit with the hash 54eb79a5590d1716b9ac335457230d771181f4a7

  • This will delete the commit. I believe this is not the AP question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.