How to Create a Patch with Git

Today I needed to transfer a few commits from my pair’s laptop to my own. Since git is a distributed source control system you can actually pull commits directly from any git repo (including someone’s local repo) – as you would from GitHub. Unfortunately this requires SSH access which we didn’t have on the (corporate) network we were on. I really wanted something simpler – I wanted to create a patch.

This is actually really easy to do with git. Basically git allows us to use the result of a diff statement as a patch. For example, if you have some local changes which are not yet committed you can run a simple ‘git diff’ to see the changes. If you want to package these changes as a patch you can simply pipe the result into a patch file.

git diff > changes.patch

Now you can apply this patch to any other repo.

git apply changes.patch

By modifying the diff statement it’s very easy to create the patch you want. In my case I wanted to package the last 4 commits as a single patch.

git diff HEAD~4 > changes.patch

Happy coding.