Chapter

Undoing things

Fix mistakes in Git safely: amend the last commit, unstage files, discard changes, reset vs revert, stash work in progress, and recover lost commits with the reflog.

Git Basics 7 Lessons from courses

About this chapter

Everyone makes mistakes in Git: a typo in a commit message, a file staged too early, a change you want to throw away, or a commit that should never have happened. This chapter is the one you'll come back to. You'll learn the safe, everyday tools - amend, restore, stash - and the sharper ones - reset, revert, reflog - so you always know how to get yourself out of trouble, and which commands are safe to run when other people share your work.

Lessons from courses

  1. 1 Amend the last commit with git commit --amend Fix your last Git commit message or add a forgotten file with git commit --amend - and why you should never amend a commit you already pushed.
  2. 2 Unstage a file in Git Unstage a file in Git with git restore --staged (or the older git reset HEAD) without losing a single edit. Here is how, and the trap to avoid.
  3. 3 Discard changes in Git How to discard uncommitted changes in Git with git restore. A destructive command with no undo - the changes are gone for good, so read first.
  4. 4 git reset --soft vs --hard explained git reset --soft vs --hard vs --mixed against HEAD~1: what each mode keeps and what it deletes, with a clear table and when to reach for which.
  5. 5 Revert a commit with git revert How to revert a commit with git revert - a new commit that cancels an old one, safe on shared branches, plus how git revert differs from git reset.
  6. 6 Stash work in progress with git stash Use git stash, pop, list and drop to shelve unfinished changes, switch branches with a clean tree, then bring your work back exactly where you left it.
  7. 7 Recover lost commits with git reflog Use git reflog to find and recover a commit that seems lost after a bad git reset, then restore it with git reset or a new branch. Git's safety net.
Git Basics Go to course