How to revert previous commit in git?

To revert a previous commit in Git, you can use the git revert command. The git revert command creates a new commit that undoes the changes introduced by a specific commit, effectively reverting those changes in the commit history. This is a safer way to undo changes compared to using git reset, as it preserves the commit history and does not alter the repository’s recorded history.

Here’s the basic syntax for reverting a commit:

git revert <commit-hash>
  • <commit-hash>: The SHA-1 hash of the commit you want to revert. You can find the commit hash in the commit history using git log.

Here are the steps to revert a previous commit:

  1. First, make sure your working directory is clean (no uncommitted changes). You can use git status to check the status of your repository.
  2. Find the commit hash of the commit you want to revert. Use git log to view the commit history, and copy the hash of the commit you wish to revert.
  3. Run the git revert command with the commit hash you want to revert. For example:
git revert abc1234

Replace abc1234 with the actual commit hash.

  1. Git will open your default text editor to enter a commit message for the revert. The default message will indicate that the revert is undoing the changes of a specific commit. You can modify the message as needed, save the file, and close the editor.
  2. A new commit will be created that undoes the changes introduced by the specified commit.
  3. Finally, push the new commit to the remote repository if needed:
git push origin <branch-name>

Replace <branch-name> with the name of the branch you are working on.

After the revert, the changes introduced by the reverted commit will be effectively undone, and a new commit will be added to the history to record the reversion. It’s important to note that git revert creates a new commit, so it’s safe to use even if the original commit has already been pushed and shared with others. The history remains intact, and the revert can be easily reverted itself if necessary.

error: Content is protected !!