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

52 lines
1.1 KiB
Markdown

# Undoing Things
## Goal
Learn safe ways to undo changes at different stages.
## Discard Unstaged Working-Tree Changes
```bash
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)
```bash
echo "line" >> notes.txt
git add notes.txt
git status
git restore --staged notes.txt
git status
```
## Amend the Last Commit
```bash
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)
```bash
# 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)
```bash
# 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.