Course outline · 0% complete

0/28 lessons0%

Course overview →

cherry-pick and detached HEAD

lesson 9-3 · ~9 min · 26/28

Borrowing exactly one commit

Merge and rebase move whole branches. Real weeks regularly need something smaller: the critical bug fix sits as one commit on a teammate's unfinished branch, or must be copied onto the released version without dragging along everything else that's on main. Shipping a fix twice by hand invites typos; Git can transplant the commit itself.

git cherry-pick <hash> takes one existing commit and applies the same change as a new commit on your current branch:

$ git switch main
$ git cherry-pick f4a5b6c
[main 8d7c6b5] Fix crash when cart is empty
 1 file changed, 2 insertions(+)

Note the hashes: the fix was f4a5b6c over there, and the copy here is 8d7c6b5 — a new commit with a new hash, because a commit's id is computed from its contents including its parent (lesson 1-2), and this copy has a different parent. That should sound familiar: rebase (lesson 9-1) is essentially cherry-pick run in a loop, replaying each of your commits onto a new base. If the change collides with your branch's lines, you get a normal unit-6 conflict, resolved the normal way.

Detached HEAD: visiting the past safely

Sometimes you want to stand on an old commit — to run the code as it was, or test whether a bug already existed back then (bisect, next unit, does this to you repeatedly). Asking to stand on a commit rather than a branch puts you in detached HEAD state:

$ git switch --detach a1b2c3d
HEAD is now at a1b2c3d Add pancake recipe

Detached means HEAD points directly at a commit instead of at a branch (lesson 5-1's HEAD → branch → commit chain loses its middle link). Looking around is perfectly safe. The danger is committing: with no branch label following you, any commit you make here is reachable by nothing once you switch away — only the reflog (lesson 4-3) remembers it, temporarily.

Git's own warning text says exactly what to do if work made in the past turns out to be worth keeping: put a label on it before leaving.

$ git switch -c fix-from-the-past

That creates a branch right where you stand, and your commits are ordinary, protected history again.

The fix you need is commit f4a5b6c on a teammate's unfinished branch. Copy just that commit onto main.

Step 1/3: Make sure you're standing on the branch that should RECEIVE the fix.

~/recipe-book $ 

Quiz

After git cherry-pick f4a5b6c succeeds on main, what exists on main?

Quiz

You git switch --detach to an old commit, make one commit there, then switch back to main. Why is that new commit at risk?

Problem

A one-commit bug fix, hash f4a5b6c, lives on another branch. Which full command applies that single commit to the branch you are standing on?