Git
Reverting a specific commit
Learn to revert a specific commit.
Reverting a specific past commit
git revert can undo any commit from the past, not just the latest one (HEAD). Even if intermediate commits were made, Git isolates the changes introduced by the target commit and applies their opposite. You supply the commit reference or hash as a parameter to the command.
# Undo a specific commit from the past:
git revert --no-edit 7b2a9c1
git revert --no-edit HEAD~1
This selective approach removes an old mistake without sacrificing any useful work in between.
Conflicts during revert
If lines altered by the targeted commit were modified again in subsequent commits, a conflict may arise. Once you resolve the conflict and stage files with git add, complete the process with git revert --continue. If you wish to give up, restore the repository using git revert --abort.
# Resolve and continue:
git add file.txt
git revert --continue
# Cancel the operation entirely:
git revert --abort
This flexibility ensures complex undo operations can be handled safely.
Exercise Revert a commit from history
Revert the HEAD~1 commit with git revert --no-edit -q HEAD~1 and print the latest commit subject with git log -1 --format="%s".
Show example solution
git init -q -b main
git config user.name "Bahar"
git config user.email "bahar@example.com"
echo "a" > a.txt
git add a.txt
git commit -qm "A eklendi"
echo "b" > b.txt
git add b.txt
git commit -qm "B eklendi"
echo "c" > c.txt
git add c.txt
git commit -qm "C eklendi"
git revert --no-edit -q HEAD~1
git log -1 --format="%s"
Test yourself
-
What do you do when you want to undo a specific commit after several other commits have been made?
- Pass the commit's hash as a parameter to the git revert command
- Manually delete the past commit file from the .git folder
- Delete the past commit from the stack with git stash drop
- Reset the repo to that commit with git reset --hard, deleting all work in between
Show answer
Pass the commit's hash as a parameter to the git revert command — git revert <hash> inverts only the changes of the specified commit without affecting intermediate commits.
-
Abort revert operation
git revert ____
Show answer
git revert --abort
-
Commit revert commands
- git revert <hash>
- Inverts the specified commit
- --continue
- Completes revert after conflict fix
- --abort
- Aborts the revert operation
- Seçici geri alma
- Leaves intermediate commits intact
Next lesson: Summary - Revert