Recover commits with reflog and move selected changes with cherry-pick
Recover commits with reflog and move selected changes with cherry-pick
Many Git mistakes are less final than they first appear. If a branch was reset or deleted locally, the commit may still be reachable through the reflog for a while.
What you’ll learn
- Use reflog for local recovery.
- Create a recovery branch.
- Apply a selected commit with cherry-pick.
Recover before you panic
Mistake
A branch pointer moved away from useful work.
commit looks lostReflog
Find where HEAD or the branch pointed earlier.
old hashPreserve
Create a branch or tag before further edits.
recovered-work
Reflog records local reference movement
git reflog records where local references such as HEAD have pointed. It is a recovery aid, not shared project history. You can create a branch at a recovered hash to make the commit reachable again.
git cherry-pick <commit> applies the change introduced by a selected commit onto the current branch, creating a new commit. Use it when one specific change belongs on another line of history, not as a default replacement for proper branch integration.
Recover first; rewrite second
Run this in a disposable practice repository unless the lesson explicitly says otherwise.
git reflog
# find the desired old hash
git switch -c recovered-work <old-hash>
# on another branch
git cherry-pick <commit-hash>When you are unsure after a reset or rebase, inspect reflog before making more destructive changes. Creating a new branch at the desired commit is a conservative way to preserve it.
Practice: Reflog, cherry-pick and recovery
Your task: In a disposable repository, make a commit, reset the branch to the previous commit, then use reflog to find the lost tip and create a recovery branch there.
Common pitfall to avoid
Reflogs are local and expire according to Git maintenance rules; they are not a backup strategy. Important work should be committed and pushed to an appropriate remote.
Check your understanding
Reflog, cherry-pick and recovery: what to remember
Recover commits with reflog and move selected changes with cherry-pick is complete when you can explain the state being changed before you run the command, not merely repeat the syntax.
Read further: official supporting documentation.
Reaching the recap and completing the quizzes are separate milestones.