67db91dd-3847-4b3f-9b8d-392.../docs/08-undoing-things.md

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 tree
  • git 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.