Viewing History and Undoing Mistakes
Reading history
git log --oneline --graph --decorate --all # the whole picture
git log -p app.py # every change to one file
git log --author="Ada" --since="2 weeks ago"
git show a1b2c3d # one commit in full
git blame app.py # who last changed each line
git diff main..feature # compare branches
Make the first one an alias: git config --global alias.lg "log --oneline --graph --decorate --all".
Undoing, by situation
| Situation | Command |
|---|---|
| Discard unstaged edits to a file | git restore app.py |
| Unstage a file (keep the edits) | git restore --staged app.py |
| Fix the last commit message or add a forgotten file | git add file && git commit --amend |
| Undo a commit that is already pushed | git revert <sha> |
| Throw away local commits (not pushed) | git reset --hard <sha> |
| Move the last commit back to staging | git reset --soft HEAD~1 |
revert vs reset
git revertcreates a new commit that undoes an old one. History is preserved, so it is safe on shared branches.git resetmoves the branch pointer backwards, erasing commits from the branch. Only use it on commits nobody else has.
Rule of thumb: if it has been pushed, revert. If it is only local, reset is fine.
The safety net: reflog
Git records every position your branch has been at, even after a reset:
git reflog
# 9f8e7d6 HEAD@{0}: reset: moving to HEAD~3
# 4c5b6a7 HEAD@{1}: commit: Add payment webhook
git reset --hard 4c5b6a7 # your "lost" commits are back
Commits are very hard to truly lose in Git. Uncommitted work, however, is not protected, so commit often.
Stash: put work aside
git stash push -m "half-done navbar"
git switch main # fix something urgent
git switch feature
git stash pop # bring the work back
git stash list
Practice
In a test repository, make three commits, git reset --hard HEAD~2, then recover them with git reflog.
Check yourself
- Which undo command is safe on a branch your team uses?
- How do you recover from an accidental
git reset --hard? - What does
git restore --stageddo to your edits?
Ihr Fortschritt wird nur in diesem Browser gespeichert.
Zur Prüfung einreichen (10 Punkte)