Git Advanced Guide — Rebasing, Cherry-Pick, and Recovering Mistakes

Advanced Git workflows: interactive rebase, cherry-pick, bisect, reflog, stash, and how to safely undo commits and recover lost work.

Interactive Rebase

Interactive rebase lets you edit, reorder, squash, or drop commits before pushing. It's the cleanest way to tidy up a feature branch.

# Rebase the last 4 commits interactively
git rebase -i HEAD~4

# In the editor, change pick to:
# s (squash) — combine with previous commit
# r (reword) — edit the commit message
# d (drop) — remove the commit entirely
# e (edit) — pause to amend files

Cherry-Pick

Cherry-pick applies a specific commit from another branch to your current branch — useful for backporting a fix without merging the entire branch.

# Apply a single commit
git cherry-pick abc1234

# Apply a range of commits
git cherry-pick abc1234..def5678

# Cherry-pick without committing (stage the changes only)
git cherry-pick -n abc1234

Finding Bugs with git bisect

git bisect start
git bisect bad                  # current commit has the bug
git bisect good v2.0.0          # this tag was working

# Git checks out a commit halfway between good and bad
# Test it, then mark it:
git bisect good   # or: git bisect bad

# Repeat until bisect identifies the first bad commit
git bisect reset  # return to original HEAD

Recovering with git reflog

The reflog records every HEAD movement — including commits that no longer exist in any branch. This is your safety net when you think you've lost work.

# See all recent HEAD movements
git reflog

# Output:
# abc1234 HEAD@{0}: reset: moving to HEAD~1
# def5678 HEAD@{1}: commit: add feature X

# Restore a lost commit
git checkout def5678         # detached HEAD
git checkout -b recovery     # save as a branch

Stashing Work in Progress

# Stash uncommitted changes
git stash push -m "WIP: feature X"

# List stashes
git stash list

# Apply and drop the latest stash
git stash pop

# Apply a specific stash without dropping it
git stash apply stash@{2}

Frequently Asked Questions

What is the difference between merge and rebase?

Merge preserves history by creating a merge commit. Rebase rewrites history to create a linear commit graph. Use merge for public branches; use rebase to clean up feature branches before merging.

How do I undo the last commit but keep the changes?

git reset --soft HEAD~1 undoes the commit but keeps changes staged. git reset HEAD~1 unstages them. git reset --hard HEAD~1 discards them — use with caution.