Hands-On: Reset Lab
Hands-On: Reset Lab
Walk one commit through soft, mixed, and hard on desk-api. Lose the line on purpose, and take it back from the reflog.
Setup
cd ~/desk/desk-api
git switch main
git status
START=$(git rev-parse HEAD)
echo "$START"Status is clean, aside from ignored files such as .env. If git switch main refuses, restore or commit the work left from the previous page.
echo "lab line" >> README.md
git add README.md
git commit -m "lab: scratch line"Soft
git reset --soft HEAD~1
git status
git diff --staged -- README.mdThe line is under “Changes to be committed”. git log --oneline does not show lab: scratch line.
git commit -m "lab: scratch line"Same tree, new hash. The next mode starts from a commit again.
Mixed
git reset HEAD~1
git status
git diff -- README.mdGit prints Unstaged changes after reset:. The line is in the file and not in the index.
git add README.md
git commit -m "lab: scratch line"Hard, and an untracked file
echo "not tracked" > notes.tmp
git reset --hard HEAD~1
git status
grep "lab line" README.md || echo "line gone"
ls notes.tmpTracked files match the commit in $START. notes.tmp is still in the directory. --hard left it there.
Recover with the reflog
git reflog -5The first line is this reset (HEAD@{0}). The next line (HEAD@{1}) is commit: lab: scratch line. HEAD@{1} means “where HEAD was one move ago.” That is a different question from HEAD~1, the parent of the current commit. Chapter 17 is that difference in full.
git reset --hard HEAD@{1}
grep "lab line" README.md
git log --oneline -1The line is back. main names the scratch commit again.
Leave the repo as you found it
git reset --hard "$START"
rm -f notes.tmp
git status
git log --oneline -5$START is the tip from the start of the lab, so this last reset also drops lab: scratch line.
Done when
git statusis clean (an ignored.envis fine)notes.tmpis gone- the log has no
lab: scratch line README.mdhas nolab line- you saw that line staged, then unstaged, then missing, then restored from
HEAD@{1}
Chapter 8 creates branches from this same desk-api. A reset of shared main waits; merging and rebasing come first.