git / Guides

Undo a Git commit: reset, revert or restore?

Start with what you want to keep: the file changes, the commit history, or both. Then check whether anyone else already has the commit.

Examples use Bash; consult the references for details of your environment.

Choose by the state of your work

SituationCommandResult
Unstage a filegit restore --staged -- file.txtKeeps the edits in your working tree.
Undo the last local commit, keep edits stagedgit reset --soft HEAD~1Moves the branch back one commit.
Reverse a commit already sharedgit revert <commit>Adds a new commit reversing that change.

Check git status and git log --oneline -5 first. The reset example needs a parent commit and applies to a private branch. A merge commit needs separate consideration; do not guess a mainline parent.

Try a local reset in a disposable repository

Use a new, empty directory outside your project. This exercise creates two commits, removes the second from the branch history and leaves its edit staged.

git init -b main
git config user.name "DevSheet Demo"
git config user.email "demo@example.invalid"
printf "one\n" > note.txt
git add note.txt
git commit -m "First note"
printf "two\n" >> note.txt
git commit -am "Second line"
git reset --soft HEAD~1
git status --short
git diff --cached

Expected: M note.txt in the short status, and an added two line in the staged diff. The file still contains both lines.

Reverse a shared commit

With a clean working tree, inspect the commit and run the following, replacing the example hash with your own. Git normally opens an editor for the new commit message.

git show a1b2c3d
git revert a1b2c3d
git status

Later changes may conflict with the reversal. Resolve the files and use git revert --continue, or cancel this operation with git revert --abort. A revert does not erase the original commit or a secret it contained.

Avoid losing work

git reset --hard can discard uncommitted tracked edits and overwrite obstructing untracked paths. It is unnecessary for the exercise above.

git restore -- file.txt replaces unstaged tracked edits; adding --staged changes the index instead. If a branch was moved by mistake, inspect git reflog and create a recovery branch at the verified old commit. Reflog cannot recover every uncommitted edit.

References

All guides