Roll back commits

In Git, if you make a mistake, you can undo or roll back your changes. For more details, see Undo options.

Undo commits by removing them

  • Undo your last commit and put everything back in the staging area:

    git reset --soft HEAD^
    
  • Add files and change the commit message:

    git commit --amend -m "New Message"
    
  • Undo the last change and remove all other changes, if you did not push yet:

    git reset --hard HEAD^
    
  • Undo the last change and remove the last two commits, if you did not push yet:

    git reset --hard HEAD^^
    

Git reset sample workflow

The following is a common Git reset workflow:

  1. Edit a file.
  2. Check the status of the branch:

    git status
    
  3. Commit the changes to the branch with a wrong commit message:

    git commit -am "kjkfjkg"
    
  4. Check the Git log:

    git log
    
  5. Amend the commit with the correct commit message:

    git commit --amend -m "New comment added"
    
  6. Check the Git log again:

    git log
    
  7. Soft reset the branch:

    git reset --soft HEAD^
    
  8. Check the Git log again:

    git log
    
  9. Pull updates for the branch from the remote:

    git pull origin <branch>
    
  10. Push changes for the branch to the remote:

    git push origin <branch>
    

Undo commits with a new replacement commit

git revert <commit-sha>

The difference between git revert and git reset

  • The git reset command removes the commit. The git revert command removes the changes but leaves the commit.
  • The git revert command is safer, because you can revert a revert.
# Changed file
git commit -am "bug introduced"
git revert HEAD
# New commit created reverting changes
# Now we want to re apply the reverted commit
git log # take hash from the revert commit
git revert <rev commit hash>
# reverted commit is back (new commit created again)