Back

Explore Courses Blog Tutorials Interview Questions
+6 votes
2 views
in DevOps and Agile by (19.4k points)
edited by

I accidentally committed the wrong files to Git, but I haven't pushed the commit to the server yet.

How can I undo those commits from the local repository?

1 Answer

+6 votes
by (27.5k points)
edited by

Case 1: Say, C is our HEAD and (F) is the state of our files. Now we want to remove C.

From this:

image

To get this: 

image

We will use this command:

git reset --hard HEAD~1

Here, B becomes the HEAD. Because we used --hard, our files are now reset to their state at commit B.

Remember that: HEAD is just a pointer to our latest commit. When we do a git reset HEAD~1, we tell Git to move the HEAD pointer back one commit. If we don’t use --hard, then that means  we are leaving our files as they were. Let us take a look at another scenario. 

Case 2: Say, we don’t want to nuke the commit C, we just want to undo the commit but keep our changes for a bit of modification. Then we will do this: 

From this:

image

To get this: 

image

We will be using this command: 

git reset HEAD~1

Case 3: We can also undo our commit but leave our files and our index:

git reset --soft HEAD~1

This command will not only leave our files alone, but also will not touch our index. When we do git status, after this command, we'll see that the same files are in the index as before. In fact, right after this command, if we do git commit and we'd be redoing the same commit you just had.

For more details about branching in git go through this crash course of git all your doubts will clear:

Browse Categories

...