How to Undo a Commit in Git ?
Basically, you did the last commit in your local repository and have not pushed back to the public repository or simply you want to change, basically, you do not want to do that commit so you wanted to undo the commit but in generic, there arise two cases where undo a commit is needed and possible sometimes as follows:
- Undo a commit From the local repository
- Undo a commit from the public repository
Case 1: Undo a commit from the local repository
1.1 First check your all commits
Output: commits are just examples or sample commits
commit 2: second commit commit 1: First commit
Perception drawn are as follows:
- commit 2 is the commit you want to undo, the current head is here
- commit1 is the first commit where you want to go after undo
1.2 To restore everything or undo all the changes we have to reset the commit.
#git reset --soft HEAD^
#git reset --hard HEAD^
- soft is used if you want to keep your changes
- hard is used if you don’t want to keep your changes
1.3 To check your commit is reset or not
commit 1: First commit //undo the second commit, now head is at first or previous commit
One can clearly see last commit (i.e. second commit) is removed.
Case 2: Undo a commit from the public repository
Now if we have already made your commit public then you will have to create a new commit which will “revert” the changes you made in your previous commit (current HEAD) then do follow the certain commands:
- Reverting changes
- Checking all commits to see the list of commits
2.1 revert your changes
#git revert HEAD
We are now ready for your new commit in order to restore the file that we accidentally have remove with the below command as follows:
#git commit -m
2.2 Now check your all commits to see the list of commits
commit 3: restoring the file that we accidentally remove commit 2: removing a file we don't need commit 1: Needed file
Now we can revert your last commit.
Also do note that we use the command below specified to undo the last commits in git where the head is a pointer pointing to the last commit in our branch
git reset HEAD~<no-of-commits>