Skip to content

Undo changes safely

Undoing mistakes · Article 7 of 9 · 3 min read

Know which undo command touches what before you run one.

The short version

Use git restore to throw away edits in a file. Use git revert to undo a commit by adding a new one. Both are safe to use on shared history.

Details

git restore discards uncommitted changes and cannot be undone, so check git diff first. git revert leaves the original commit in place and records its opposite, which is why it is safe after you have pushed.

Try it yourself

echo "oops" >> notes.txt
git restore notes.txt
git log --oneline -1
git revert HEAD

After the restore, notes.txt is back to its last committed text. After the revert, a new commit appears that undoes the latest one.

Explain it to the duck

Why is revert safer than deleting a commit once it has been pushed?

Tested with: Git 2.51.

Where to go next