Git
git revert
Learn to create a reverse commit with git revert.
Safe undo with git revert
The git revert command creates a brand new commit that inverts the changes introduced by an earlier commit. Instead of deleting or rewriting history, it records the opposite of the operation as a forward-moving commit. This keeps project history intact and avoids conflicts with team repositories.
# Invert the HEAD commit:
git revert HEAD
This is the safest way to undo mistakes, especially on branches shared with others.
Skipping commit editor: --no-edit
Normally, when git revert runs, Git automatically prepares a commit message and opens the terminal editor. To accept Git's default revert message directly without opening an editor, pass the --no-edit flag. If you want to stage the inverted changes without committing immediately, use -n.
git revert --no-edit HEAD
git revert -n HEAD
The --no-edit flag is especially handy in scripts and quick fixes.
Exercise Undo latest commit with revert
Undo the latest commit using git revert --no-edit -q HEAD and print that the file returned to its initial state using cat app.py.
Show example solution
git init -q -b main
git config user.name "Bora"
git config user.email "bora@example.com"
echo "v1" > app.py
git add app.py
git commit -qm "v1 hazir"
echo "hatali kod" >> app.py
git add app.py
git commit -qm "Hatali ekleme"
git revert --no-edit -q HEAD
cat app.py
Test yourself
-
What does Git do when the git revert HEAD command is executed?
- Permanently deletes and removes the HEAD commit from the repo
- Creates a new commit that reverses the changes introduced by HEAD
- Moves all files in the working directory to the staging area
- Updates only the author name and date of the latest commit
Show answer
Creates a new commit that reverses the changes introduced by HEAD — git revert keeps history safe by producing a new commit containing the inverse of the target commit's changes.
-
Accept default revert message directly
git revert ____ HEAD
Show answer
git revert --no-edit HEAD
-
git revert fundamentals
- git revert
- Creates a new inverse commit
- Ters commit
- Removes added lines, adds deleted ones
- --no-edit
- Directly accepts the default message
- -n
- Reverts but does not commit
Next lesson: revert vs reset