Frequently asked questions around Git and Version Control.
How to Create and Apply a Patch in Git
Patches are an alternative way to exchange code changes. Although today - with the widespread use of remote repositories, forks, and Pull Requests - exchanging code via patches isn't very common anymore, it can be a valuable tool in special situations.
By creating a patch, you can essentially "export" one or more commits into plain text files, which you can then easily send to someone else for integration.
In this short article, we'll look at how to both create and apply patches.
The Git Cheat Sheet
No need to remember all those commands and parameters: get our popular "Git Cheat Sheet" - for free!
To create a patch, we will use the git format-patch command. Most importantly, we must tell Git which commits exactly we want to be included in the patch. Let's take the following scenario as an example:
we are currently on a bugfix branch named "bugfix/broken-navigation"
we had based the branch on our local "master" branch
after some work, we have created two new commits on the bugfix branch
we now want to create a patch that contains these two new commits so we can send them to a colleague that wants to integrate them
We can achieve this with the following commands:
# Switch to the base branch that is missing the new changes
$ git checkout master
# Create patch files for all new commits in our bugfix branch
$ git format-patch bugfix/broken-navigation
The git format-patch command will include all of the commits that are contained in the specified branch ("bugfix/broken-navigation"), but not in the currently checked out branch ("master").
This will leave us with two patch files, which contents look approximately like this: