How to recover the previous commit?

15

After adding modified file and having commit , I had to modify the entire structure of the code, but it did not work and I wanted access to the previous code again.

How do I retrieve content from the previous commit ?

    
asked by anonymous 24.12.2014 / 22:20

3 answers

14

You can use the following command:

git reset HEAD~1

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

git reset --hard HEAD~1
    
24.12.2014 / 22:44
5

To undo the last commit you can do:

$ git reset --soft HEAD^

In this way you will lose the commit but keep all the code that you have committed and the current state before resetting.

If you want to see what was done in the last commit, you can do:

$ git log -p -2

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

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

$ git checkout 12345678901234567890123456789012345678ab
    
24.12.2014 / 23:05
1

The steps I usually take to get the code into a certain state of development are:

  • List the commits done:

    git log
    
  • Identify what commit I'm interested in resetting 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
    
  • reset , pointing to hash of commit that I want to be the new state of the code:
    git reset --hard 54eb79a
    
  • Now the whole code is in the state it was in after commit with hash 54eb79a5590d1716b9ac335457230d771181f4a7

        
    26.12.2014 / 23:00