Member-only story
How to Undo Changes in Git
The CMD+Z or CTR+Z in Git World with practical examples
In this tutorial, we will show you how to “undo” changes in Git with walk-through examples.
How to Undo a Deleted File
Assume that accidentally we removed a file. Let’s remove the “myfile.txt“
git rm myfile.txt
git status

So if we want to restore the file, we can run:
git restore myfile.txt

How to Unstage a File
Let’s say that you accidentally staged a file by running the command “git add myfilename” and you want to unstage the file. Then you can simply run:
git reset HEAD myfilename
How to Retrieve Older Versions
Let’s say that we want to retrieve an older version of a file. Let’s see how we can do it. We have to go to the log history by running the “git log” command and choose the SHA code of the older version (the first characters are enough). Then you run the command “git checkout <SHA>”. For example:
git checkout 0dd6680
And you will get the following message:
Note: switching to '0dd6680'.You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by switching back to a branch.If you want to create a new branch to retain commits you create, you may do so (now or later) by using -c with the switch command. Example: