git revert undoes the changes of an earlier commit by making a new commit that does the opposite. The original stays in the history.
Revert one commit
Find the commit you want to undo:
$ git log --oneline
c91d044 (HEAD -> main) Change price to 0
a07b3f5 Add price listThen revert it:
$ git revert c91d044
[main 5be2f10] Revert "Change price to 0"
1 file changed, 1 insertion(+), 1 deletion(-)Git opens your editor with a prepared message. Save and close it, or add --no-edit to accept the message as it is. The log now has three commits, and the file content matches what it was before the bad change.
Because revert only adds a commit, it is safe on branches that others already use. They pull it like any other work. git reset --hard is different: it moves the branch back, discards uncommitted changes to tracked files, and rewrites what the branch contains.
Reverting older commits
You can revert any commit, not just the latest. Only that commit's changes are reversed, not everything after it. git revert HEAD~1 reverses the second newest commit.
If later commits touched the same lines, you may get a conflict. Fix the file, then:
$ git add prices.txt
$ git revert --continueOr give up and return to where you started with git revert --abort.
Useful options
-n (or --no-commit) applies the reverse changes to the working tree and staging area without committing, so you can adjust them or combine several reverts:
$ git revert -n c91d044
$ git commit -m "Restore old price"Reverting a merge commit needs -m with a parent number, for example git revert -m 1 <merge>, which usually keeps the branch you merged into. Merging that same branch again later will not bring the reverted changes back by itself, so read the documentation before doing this.
Revert does not remove secrets. A password committed earlier is still in the history, so change the password. The details are in the git revert documentation.
Try it
Make three commits that each add a line to a file. Revert the middle one, resolve any conflict, and read the file and git log --oneline.
Check your understanding
git revert
All 4 sections · no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.