appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Undoing mistakes safely

Lesson 4 of 49 minBeginner

Restore files, amend commits, revert and stash.

Almost everything in Git can be undone, if you pick the right tool. The key question: has the commit been shared?

SituationCommand
Discard edits to a file you have not stagedgit restore file.txt
Unstage a file but keep the editsgit restore --staged file.txt
Fix the last commit message or add a forgotten filegit commit --amend
Undo a commit that is already sharedgit revert <commit>
Park unfinished work for latergit stash then git stash pop
See where HEAD has been, to recover lost commitsgit reflog

revert vs reset

git revert adds a new commit that cancels an old one: history stays intact, so it is safe on shared branches. git reset --hard moves the branch back and discards work: use it only on local, unshared commits.

Carefulgit reset --hard and git restore on unsaved edits permanently delete changes that were never committed.

Inspecting before acting

git diff                  # unstaged changes
git diff --staged         # staged changes
git show <commit>         # one commit in detail
git log --oneline --graph # the shape of the history

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

Hintgit restore and the file name.
HintThink of a stash of things.
3. A bad commit is already pushed to a shared branch. What is the safest fix?
4. Which command lists where HEAD has been so you can recover lost commits?

Key terms