![]() |
Git offers several ways to backtrack and correct mistakes, making it a powerful tool for developers. In this article, we will explore various methods to undo a commit in Git, ensuring that you can choose the best approach for your specific system. Below are the approaches to Undo a commit in Git: Table of Content Understanding Git CommitsBefore learning the methods, it’s essential to understand what a commit in Git represents. A commit is a snapshot of your project’s files at a specific point in time. A unique SHA-1 hash identifies each commit. When you want to undo a commit, you are essentially changing the history of these images. Methods to Undo a Commit in Git1. Using Git resetStep 1: First check all your commits#git log Output: commits are just examples or sample commits commit 2: second commit Perception drawn are as follows:
Step 2: To restore everything or undo all the changes we have to reset the commit.#git reset --soft HEAD^ #git reset --hard HEAD^
Step 3: To check your commit is reset or not #git log Output: commit 1: First commit One can clearly see last commit (i.e. second commit) is removed. 2. Using Git revertNow 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). Step 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 Step 2: Now check your all commits to see the list of commits #git log Output: commit 3: restoring the file that we accidentally remove 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>
3. Using git checkoutThe git checkout command can be used to create a new branch from a specific commit. This method is helpful when you want to keep the original branch unchanged. Steps to create a new branch from a specific commit: 1. Identify the commit hash you want to create a branch from.
2. Use the ‘git checkout’ command to create a new branch.
Example:
|
Reffered: https://www.geeksforgeeks.org
Git |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |