Five Git commands to undo mistakes without panicking

Committed to the wrong branch, lost your changes, need to fix the last commit? Five Git commands to undo mistakes safely, for situations everyone runs into.

Git rarely loses data for good. Most "disasters" can be rescued if you know the right command and don't panic.

1. See everything that has happened

bash
git reflog

reflog records every position HEAD has ever pointed to. A commit that "disappeared" after a reset is still listed here.

2. Fix the last commit before you push

bash
git commit --amend

3. Move a commit to the right branch

bash
git switch right-branch
git cherry-pick <commit-hash>

4. Put unfinished changes aside for a moment

bash
git stash push -m "fixing the header"
git stash pop

5. Undo safely on a shared branch

bash
git revert <commit-hash>

Get the next post by email.

One email a week, only when there is something worth reading. No spam.