How to Use Patch Files in Git

A patch is a file that contains the changes of one or more commits. It also includes metadata of the commit, such as the commit date, commit message, and so on. You can generate a patch from commits and it will be possible for other developers to apply it to their repositories. It is generally used when someone doesn't have writing access but you want to take the changes that he has made.

Generating Patch Files from Commits

To generate a patch file the git format-patch command is used.

Generating patch files for the given number of commits

If you want to create patches for the given number of commits coming before the selected one, then you can use the git format-patch with the -N option (N specifies the number of commits you want to create patches for):

git format-patch -N <sha1-commit-hash>

Instead of the commit hash, you can use HEAD as follows:

git format-patch -N HEAD

Generating patch files for the given range of commits

Instead of specifying the number of commits, you can indicate the range of commits to create patches for them. Here is how to do it:

git format-patch <first-commit-hash>^..<end-commit-hash>
To create a single patch file for multiple commits, you should add the --stdout > file.patch to the commands above.

Viewing the changed files inside the patch

To view the changes that have been made inside the patch file, you can use the git apply command with the --stat option, mentioning the patch file:

git apply --stat file.patch

Checking for errors

While applying patches, errors can occur. To avoid them, we recommend you to check for errors before applying a patch, by using the command below:

git apply --check file.patch

Applying the patch

Finally, to apply the patch file, you should run the command below:

git am < file.patch

The git format-patch Command

The git format-patch prepares each git commit with its patch in one file per commit. It is formatted to resemble the UNIX mailbox format. The result of the command is convenient for email submission or for use with git am.

The git apply Command

The git apply command applies a patch to files or the staging area. Reads the supplied diff output and applies it to files. The patched paths outside the directory are ignored when running from a subdirectory in a repository. The --index option attached the patch to the staging area while the --cached option attached the patch only to the staging area. The command applies the patch only to the files without these options and does not require them to be in git repository.