Stash & Reset
Save work temporarily and undo changes
Skills taught: git.stash, git.reset, git.restore
git stash — save work aside
# You have uncommitted changes but need to switch branches
git stash
# → Saved working directory and index state
# Give your stash a name (recommended)
git stash push -m "half-finished login form"
# List all stashed items
git stash list
# → stash@{0}: On feature: half-finished login form
# → stash@{1}: WIP on main: a3b2c1d Update footer
# Restore most recent stash (and remove from stack)
git stash pop
# Restore a specific stash entry (keep in stack)
git stash apply stash@{1}
# Drop a specific entry
git stash drop stash@{1}
# Include new untracked files in the stash
git stash --include-untracked
git reset — undo commits
# --soft: undo commit, keep changes STAGED
git reset --soft HEAD~1
# Useful: fix the commit message or add a forgotten file
# --mixed (default): undo commit, keep changes in working tree (unstaged)
git reset HEAD~1
# Useful: split a commit into smaller ones
# --hard: undo commit AND discard all changes (DESTRUCTIVE!)
git reset --hard HEAD~1
# ⚠️ Changes are gone. Only safe if you haven't pushed.
# Recover from --hard with reflog
git reflog
# → a3b2c1d HEAD@{1}: commit: Add login form ← find this hash
git reset --hard a3b2c1d # go back to it
git restore — discard file changes
# Discard unstaged changes in a file (UNRECOVERABLE)
git restore index.html
# Unstage a file (keep changes in working tree)
git restore --staged index.html
# Restore a file to its state 2 commits ago
git restore --source=HEAD~2 index.html
# For pushed commits — use revert instead of reset!
git revert HEAD # creates a new commit undoing the last one
git revert a3b2c1d # reverts a specific commit
Warning: git reset --hard and git restore can permanently discard work. Always check git status before using them. For pushed commits, use git revert instead — it's reversible.
Frequently Asked Questions
I did git reset --hard and lost changes. Can I recover them?
Maybe. Run git reflog to find the SHA of the commit before the reset. Then git reset --hard <that-sha> to go back. This works as long as Git's garbage collector hasn't run (usually 30+ days). git fsck --lost-found can also find dangling objects.
What is git revert and when should I use it instead of reset?
git revert <hash> creates a new commit that undoes the changes of the specified commit — it does NOT rewrite history. Use it whenever the commit you want to undo has been pushed to a shared branch. Reset is for local-only history; revert is for shared history.