Sometimes, they want additional changes in the files before committing. As a consequence, it is required to revert or remove the commit from the Git log history. For this purpose, the “$ git reset –soft HEAD~1” command is useful.
In this guide, we will learn how to undo a commit in Git.
How to Undo a Commit in Git?
To undo a commit in Git, first, navigate to Git local repository, and create and add the new file to the repo. Then, commit changes. After that, perform the main operation, which is to undo the commit using the “$ git reset –soft HEAD~1” command. One more thing that users should know is that the command will only undo the commit. However, the changes will be saved in the index.
Let’s try to implement this scenario step by step!
Step 1: Navigate to Git Directory
First, move to Git local repository:
Step 2: Create File
Create a new text file by utilizing the “touch” command:
Step 3: Track File
Now, execute the provided command to add a file to the staging area:
Step 4: Commit Changes
Next, commit the changes to the Git repository to save updates:
Step 5: Check Log History
Check the log history of the Git repository and verify the committed changes:
As you can see, currently HEAD refers to the most recent commit:
Step 6: Undo Commit
Now, undo the commit changes using the provided command:
Here, the “–soft” option is used to preserve changes made to our file, and “HEAD~1” indicates that HEAD will be reverted to the previous commit:
Step 7: Check Status
Now, verify the undo changes using the “git status .” command:
As you can see, the file still exists at the index, which means that only the commit was removed:
Step 8: Check Log History
Now, check the log history and the current position of the HEAD:
As you can see, the commit is removed from Git log history, and HEAD is referring to the “main” branch:
That’s all! We have compiled the easiest method to undo a commit in Git.
Conclusion
To undo a commit in Git, first, navigate to the Git local repository. Create a new file and track it to the staging area using the “$ git add <file-name>” command. Then, commit changes, and display the log history by executing the “$ git log –oneline –graph” command. After that, run the “$ git reset –soft HEAD~1” command to revert the commit changes. This guide explained how to undo a commit in Git.