Study notes · 11% of the exam

Undoing Changes: Reset, Revert, Restore, Reflog and Stash

Know exactly which of the three trees (HEAD, index, working tree) each undo command touches, which undos are safe on shared history, and how to get back from mistakes with the reflog.

Key points

  1. 1

    git restore <path> rewrites the working tree from the index; git restore --staged <path> rewrites the index from HEAD. --source=<commit> picks another source.

  2. 2

    git reset moves the branch: --soft stops there, --mixed (default) also resets the index, --hard also resets the working tree. --keep and --merge are safer hard resets.

  3. 3

    Path-limited git reset <commit> -- <path> only rewrites the index entry; --soft and --hard reject paths.

  4. 4

    git revert adds an inverse commit, so it is the safe undo for published history. Merges need -m 1, and re-landing a reverted merge means reverting the revert first.

  5. 5

    The reflog (HEAD@{n}, ORIG_HEAD) recovers commits after a bad reset or deleted branch. It is local only, and by default expires after 90 days (reachable) and 30 days (unreachable).

  6. 6

    git stash saves tracked changes; -u adds untracked files and -a ignored ones. A conflicting pop keeps the entry, and pop --index restores what was staged.

  7. 7

    git clean removes untracked files only with -f; add -d for directories, -x to include ignored files, or -X for ignored files only. Preview with -n.

Common traps

  • git reset --hard leaves untracked files but deletes files that were staged and never committed. Unstaged edits it discards cannot be recovered.

  • Reverting a merge undoes its content, not its history: merging the same branch again brings nothing back until you revert the revert.

  • Plain git stash pop brings staged changes back unstaged, and a dropped stash is only recoverable as a dangling commit until gc prunes it.

Test yourself on Undoing Changes: Reset, Revert, Restore, Reflog and Stash

Ten questions, with the answer and explanation after each one.