Git move commit to another branch

Rubymine’s stellar Git integration means that I seldom have to tinker with Git on the command line, but an exception to this is when I switch branches and forget to switch back before making my next commit. D’oh!

The answer is git cherry-pick.

The syntax is simple:

git cherry-pick [commit ID]

You can run “git log” to get the ID of your commit. You can also use a graphical tool like Giggle, which lets you see all commits to all branches.

If you had the misfortune of your checkin not being on any given branch, you can run “git reflog” to see all checkins to all branches, and merge your master branch with the fake branch that your checkin went to. See Stack Overflow for more details on what to do in this scenario.

One Reply to “Git move commit to another branch”

  1. Thanks for that; just came in very handy.

    I cherry-picked two commits (in the one command) from a branch to master.

    That meant I had duplicate commits. I wanted to rebase the branch to master so the branch could take advantage of these commits, but I didn’t want the branch to _contain_ the commits.

    $ git rebase –onto master 286d5dce1

    I trusted git to ignore the duplicate commits. It ignored the first but reapplied the second. I had the same commit twice in my ‘git log’, and the content was even duplicated in the file!

    It was easy to fix this with a “git rebase -i HEAD~4” and throw away the last commit.

    Perhaps if I’d cherry-picked one commit at a time, git would have detected and ignored the duplicates later. And of course, I could have used interactive rebase to be sure…

Leave a Reply

Your email address will not be published. Required fields are marked *