Learn how to create a git patch from a previous commit.

TL;DR

## Create patch from commit a12a06c
$ git show a12a06c > temp.patch

## Apply patch
$ git apply temp.patch

Long story

Let’s look at the following scenario:

You are working on a feature1 branch and you realise your last commit should not have been committed here. You could stash it but you are not sure where you are going to need to it again; so you decide yo create a patch with it.

Method 1: git reset + git diff > patch

Since that commit was our last commit, we can rewind our history 1 step and create a patch from the current diff.

  • Rewind one step and keep changes staged
$ git reset --soft HEAD~1 

Using --soft will keep our changes staged.

  • Create the patch

Create the patch from your stages changes by using

$ git diff --cached > patch1.patch

And you have all your changes in that patch

Method 2: Create patch from commit directly

In some cases, you want to create a patch from a commit that is not the previous one. You also might not be interested in rewinding your git history.

Here is a one liner that can help you create a patch from any commit in your history.

$ git show a12a06c > patch2.patch

where a12a06c is the commit you want to create a patch from.

Apply the patch

Reminder: To apply your patch somewhere else or later on.

$ git apply patch1.patch