When working with other developers on a shared repository, it is important to maintain a clean commit history. If Git users commit changes that are not ready for review or sharing, it is beneficial to undo those commits before others see or merge them into their work.
This blog will elaborate:
How Can I Undo a “git commit” Locally?
To undo a “git commit” locally, follow the below-stated steps:
-
- Redirect to the local Git directory.
- View Git log history with the help of the “git log” command.
- Run the “git reset” command along with the “–hard” option to undo the commit.
Step 1: Go Toward Local Git Repository
Run the “cd” command along with the desired local repository path and redirect to it:
Step 2: View Git Log History
Use the “git log” command to view the commit history and identify the commit that you want to undo:
As you can see, the Git log history has appeared, and we have selected “2e39cab” SHA-hash for further use:
Step 3: Undo Commit Locally
Run the “git reset” command along with the “–hard” option and set the selected commit for undoing commit locally:
The below-stated output indicates that the head is pointed on the specified commit and the above commit has been removed from the history:
Step 4: Verify the Undo Commit Operation
Execute the below-stated command to verify whether the changes have been reverted or not:
It can be seen that the commit has been reverted successfully:
How Can I Undo a “git commit” Remotely After “git push”?
After reverting or undoing the commit locally, users need to push the changes to the remote repository for removing the commit from it.
Run the following command for pushing changes from the local to the remote repository:
That’s all about undoing a “git commit” locally and remotely after “git push” in Git.
Conclusion
To undo “git commit” locally, first, redirect to the local Git directory and view the Git log history with the help of “git log”. Then, run the “git reset” command along with the “–hard” option to undo the commit. After that, run the “git push” command to push the undo commit to the remote repository. This tutorial demonstrated the method for undoing “git commit” locally and remotely after “git push” in Git.