Git Revert vs Git Reset: Undoing and Adjusting Changes in Git History

Git Revert and Git Reset are two important commands in Git for undoing and adjusting changes in the commit history of a repository. Here is a guide on how to use Git Revert and Git Reset:

 

Git Revert

  • Git Revert allows you to create a new commit to undo (revert) previously committed changes.

  • To revert a commit, use the following command:

    git revert <commit_id>
    

    Replace <commit_id> with the ID of the commit you want to revert. A new commit will be created, undoing the changes in the selected commit.

  • Revert does not alter the commit history but creates a new commit to revert the changes.

 

Git Reset

  • Git Reset allows you to go back to a previous state by moving the HEAD and current branch to a specific commit.

  • Git Reset has three different modes: --soft, --mixed (default), and --hard.

  • To reset the HEAD and current branch to a commit, use the following command:

    git reset --mode <commit_id>
    

    Replace <commit_id> with the ID of the commit you want to reset to.

  • Git Reset modes:

    • -soft: Moves the HEAD and current branch to the specified commit, keeping the changes of the previous commit in the staging area. Use the command git reset --soft <commit_id>.
    • --mixed: This is the default mode. Moves the HEAD and current branch to the specified commit and removes the changes of the previous commit from the staging area. Use the command git reset --mixed <commit_id>.
    • --hard: Moves the HEAD and current branch to the specified commit and discards all changes of the previous commit. Be cautious when using it, as any uncommitted changes will be lost. Use the command git reset --hard <commit_id>.
    <commit_id>.
  • Git Reset alters the commit history and can result in data loss, so use it with caution.

 

Git Revert and Git Reset are powerful tools for undoing and adjusting the commit history in Git. Use them carefully to ensure project stability and avoid data loss.