Git Revert: How to Undo Changes and Go Back to a Previous Commit

Step 1: Identify the Commit to Revert To

  • First, identify the commit hash or reference of the commit you want to revert to. You can use git log to see the commit history and copy the hash of the desired commit.

Step 2: Use git revert to Create a Revert Commit

  • To create a new commit that undoes changes, use the following command:
  git revert <commit-hash>

Example:

  git revert abc123

Step 3: Resolve Conflicts (if any)

  • If there are conflicts, Git will pause the process, and you’ll need to resolve them manually. After resolving conflicts, continue with git commit and git push.

Reverting Using Git User Interface (UI) Tools (e.g., GitHub Desktop)

Using a Git UI tool simplifies the process:

Step 1: Open Your Git UI Tool

  • Launch your preferred Git UI tool, such as GitHub Desktop.

Step 2: Identify the Commit to Revert To

  • In your UI tool, navigate to the commit history or the branch you want to revert.

Step 3: Select the Commit to Revert

  • In the UI, select the commit you want to revert to.

Step 4: Choose “Revert”

  • Most Git UI tools will have a “Revert” or “Undo” option for the selected commit. Click it.

Step 5: Review and Confirm

  • Review the changes that will be made by the revert commit. Once satisfied, confirm the action.

Step 6: Resolve Conflicts (if any)

  • If there are conflicts, your Git UI tool will guide you through the conflict resolution process.

Step 7: Commit and Push

  • After resolving conflicts (if any), commit the revert and push the changes to your repository.

Note:

  • Reverting creates a new commit that undoes changes. It does not remove commits or history.
  • If you want to remove commits and rewrite history, you would use git reset or git rebase, but be cautious with these commands, especially in a shared repository.