- Undo commits by removing them
- Undo commits with a new replacement commit
- The difference between
git revert
andgit reset
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:
- Edit a file.
-
Check the status of the branch:
git status
-
Commit the changes to the branch with a wrong commit message:
git commit -am "kjkfjkg"
-
Check the Git log:
git log
-
Amend the commit with the correct commit message:
git commit --amend -m "New comment added"
-
Check the Git log again:
git log
-
Soft reset the branch:
git reset --soft HEAD^
-
Check the Git log again:
git log
-
Pull updates for the branch from the remote:
git pull origin <branch>
-
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. Thegit 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)