1.1 KiB
1.1 KiB
Undoing Things
Goal
Learn safe ways to undo changes at different stages.
Discard Unstaged Working-Tree Changes
cd ~/lab-git-essentials/my-first-repo
echo "temporary" >> temp.txt
git status
git restore temp.txt # discard changes in working tree
git status
Unstage Changes (Keep Edits)
echo "line" >> notes.txt
git add notes.txt
git status
git restore --staged notes.txt
git status
Amend the Last Commit
echo "missed line" >> README.md
git add README.md
git commit --amend -m "Improve README with missed line"
git log --oneline -n 1
Revert a Commit (Safe in Shared History)
# Find a commit to revert
git log --oneline -n 5
git revert <SHA>
Reset (Be Careful)
git reset --soft <target>: move HEAD, keep index and working treegit reset --mixed <target>: move HEAD and reset index (default)git reset --hard <target>: move HEAD, reset index and working tree (destructive)
# Example: move HEAD back by 1 commit, keep changes in working tree
git reset --mixed HEAD~1
git status
Outcome
You can safely discard, unstage, amend, revert, and (carefully) reset.