DEV Community

Nikko Ferwelo
Nikko Ferwelo

Posted on

๐Ÿ”„ How to Revert a Commit in Git

Reverting a commit is useful when you want to undo changes introduced by a specific commit while preserving the commit history. Below are the methods to revert a commit.


Reverting a Commit

1. Using git revert ๐Ÿš€

The git revert command creates a new commit that undoes the changes from a previous commit, preserving the commit history.

Steps:

  1. Find the Commit Hash ๐Ÿ”: Use git log to find the hash of the commit you want to revert.
   git log
Enter fullscreen mode Exit fullscreen mode
  1. Revert the Commit ๐Ÿ”„: Use the commit hash from the previous step to revert the commit.
   git revert <commit-hash>
Enter fullscreen mode Exit fullscreen mode

Example:

   git revert a1b2c3d4
Enter fullscreen mode Exit fullscreen mode
  1. Resolve Conflicts โš ๏ธ: If there are conflicts, Git will notify you. Resolve them in your editor, then stage the resolved files.
   git add <file>
Enter fullscreen mode Exit fullscreen mode
  1. Complete the Revert โœ…: Finish the revert process by committing the changes (if Git didn't do it automatically).
   git commit
Enter fullscreen mode Exit fullscreen mode

2. Using git reset ๐Ÿ”„

The git reset command changes the current branch head to a specified state. This is useful for undoing commits in your local branch, but be cautious as it can modify commit history.

Steps:

  1. Find the Commit Hash ๐Ÿ”: Use git log to locate the commit hash you want to reset to.
   git log
Enter fullscreen mode Exit fullscreen mode
  1. Reset to the Desired Commit โš™๏ธ: Choose the reset type based on your needs:
  • Soft Reset ๐ŸŒŸ: Keeps changes in the working directory and staging area.

     git reset --soft <commit-hash>
    
  • Mixed Reset ๐Ÿงน: Keeps changes in the working directory but unstages them.

     git reset --mixed <commit-hash>
    
  • Hard Reset ๐Ÿšจ: Discards all changes and commits after the specified commit.

     git reset --hard <commit-hash>
    

Example:

   git reset --hard a1b2c3d4
Enter fullscreen mode Exit fullscreen mode

Warning โš ๏ธ: --hard will delete changes after the commit, so use it with caution.

  1. Push the Changes ๐ŸŒ: If youโ€™ve pushed the commits to a remote repository, you may need to force-push to update it.
   git push origin <branch-name> --force
Enter fullscreen mode Exit fullscreen mode

Note ๐Ÿ“: Use git revert for a safe and history-preserving way to undo commits, while git reset can be used for more drastic changes, especially in local repositories.

Feel free to reach out or follow me for more insights and tips on version control with Git. Happy coding! ๐Ÿ’ป

Connect with me:


Top comments (0)