Undoing changes: amend, revert, reset
Theory
Machine translation, not yet reviewed by a native speaker.
Git lets you fix almost anything. The main thing is to understand whether the commits have already been published (sent with push).
Fix the last commit (not yet sent):
git commit --amend -m "New message" # change the message
git add forgotten_file && git commit --amend --no-edit # add what you forgot
amend creates a new commit in place of the old one. If the old one was already on GitHub, the histories will diverge.
Undo a published commit — safely, with revert:
git revert a1b2c3d
revert creates a new commit that does exactly the opposite of the changes. The history isn't rewritten, so you can do this on shared branches too.
Roll a branch back — reset, only for local, unpublished commits:
git reset --soft HEAD~1 # undo the commit, the changes stay in the index
git reset HEAD~1 # undo the commit, the changes stay in the files
git reset --hard HEAD~1 # DANGEROUS: undo the commit and throw away the changes
HEAD~1 means "one commit back from the current one".
Your safety net — git reflog. Git remembers where HEAD pointed over the last few weeks, even after reset --hard. Find the hash you need there and go back to it: git reset --hard hash.
Put unfinished work aside: git stash hides your changes, and git stash pop brings them back. Handy when you urgently need to switch to another branch.
| situation | command |
|---|---|
| a typo in the last commit's message | git commit --amend |
| a bad commit is already on GitHub | git revert hash |
| the last local commits aren't needed | git reset |
| "I broke everything" | git reflog |
These commands aren't in the course sandbox. Practice in your own repository on your computer.