Over the past 10 months working at DigitalOcean, I’ve come to learn more about git and how it can save me from my mistakes. This past week, I used
git cherry-pick for the first time and wanted to share how you can use it as well.
While working on a ticket in a separate branch of my team’s project, I had to pause and jump back onto my
master branch to debug some errors we were seeing in production. I proceeded to commit my changes, hop onto
master, and resolve our issue. My mistake occurred when I dove back into my ticket work and somehow accidentally didn’t checkout to my separate branch. Always run
git branch before picking up where you left off!
I finished up my work and was about to commit my changes when I realized my mistake and that I was still on the
master branch. Before getting frustrated about how I was going to transfer my work to the correct branch, I thought to myself “hey, since git essentially allows us to write and edit our project history, there must be a way for me to move these changes from one branch to another”.
Off to Google I went and found the
git cherry-pick command! If you didn’t know,
cherry-pick allows you to grab a commit from one branch and write it to another branch. All you need to do is grab the the commit ID of the commit I wanted to move. Let’s breakdown the workflow.
I have my two branches
ticket-work, and we want to move a commit from
ticket-work. First, I commit those changes that I accidentally made to
master. Then, I use
git log to see the history of the commits on
$ git log commit 0a5e736cvcf6b89894894b921d4858bb34417g21 Author: jzerwick <firstname.lastname@example.org> Date: Wed Oct 2 00:11:23 2019 +0200 Implemented changes
I’ll grab the commit ID of the commit I want to move
0a5e736cvcf6b89894894b921d4858bb34417g21, hop onto my other branch, and execute
cherry-pick like so:
$ git checkout ticket-work $ git cherry-pick 0a5e736cvcf6b89894894b921d4858bb34417g21
Now all that’s left is for me to delete that unwanted commit on
This can be done by using the
reset command with the
--hard flag like so:
$ git checkout master $ git reset --hard HEAD^
HEAD^ targets the last commit, which you can also target with
HEAD~1. If you want to delete multiple commits, just specify the number of last commits after the
~ symbol. Removing the last two commits would use
And that’s it! I now have the commit on the branch I wanted and
master is back to its rightful state.