DevOpsGitHub

Advanced Git: Reflog, Cherry-Pick, and Disaster Recovery

TT
TopicTrick Team
Advanced Git: Reflog, Cherry-Pick, and Disaster Recovery

Advanced Git: Reflog, Cherry-Pick, and Disaster Recovery


1. The Reflog: The "Safety Net" of the Gods

If you delete a branch by accident (git branch -D), the commits are still in your database for about 30 days. You just lost the "Pointer."

  • The Command: git reflog
  • The Fix: Find the "Commit ID" where your branch used to be. Run git checkout -b [new_branch] [commit_id]. Boom. Your "Deleted" code is back. This command is the difference between a Junior who panics and a Senior who stays cool.

2. Cherry-Pick: Surgical Commit Moving

Imagine you fixed a major bug on the "Wrong Branch." You don't want to merge the WHOLE branch (which has 20 other messy things).

  • The Solution: git cherry-pick [commit_id].
  • It "GRABS" that one single commit and "Plasters" it onto your current branch. It is the most surgical way to move code in the Git ecosystem.

3. Interactive Rebase: Rewriting the Past

Before you send code to a PR, your history might be messy: "Commit 1: typo, Commit 2: fix, Commit 3: oops." Use git rebase -i HEAD~5.

  • It opens an editor where you can:
    • Pick: Keep the commit.
    • Squash: Combine 3 messy commits into 1 clean one.
    • Reword: Change a bad commit message.
  • You transform a "Ugly" history into a professional story that your team will love to read.

4. Git Bisect: Finding the "Zero" Bug

If your app worked on Monday but is broken on Friday, and you have 200 commits in between—where is the bug? git bisect performs a Binary Search.

  1. Tell Git a "Good" commit (Monday).
  2. Tell Git a "Bad" commit (Friday).
  3. Git will automatically jump to the middle. You test it.
  4. In about 7 jumps, Git will tell you exactly which line of code broke the app.

Frequently Asked Questions

Is Rebase dangerous? YES. Rule #1: Never rebase code that has already been pushed to a shared branch. Rebase "Rewrites" history. If you change a commit that your coworker is using, you will destroy their local repository and cause a massive conflict. Only rebase your OWN local work.

What is the 'Stash'? If you are halfway through a task but need to switch branches urgently, run git stash. It "Parks" your messy work in a temporary side-drawer. When you come back, run git stash pop to put your code back exactly where it was.


Key Takeaway

Advanced Git is about Control. By mastering the Reflog for recovery and the Rebase for curation, you gain the confidence to make bold changes without fear. You stop "Using Git" and start "Engineering History." You become the developer that your team relies on when things go wrong.

Read next: Mastering Git Internals: Objects, Blobs, and Trees →


Part of the GitHub Mastery Course — engineering the past.