How can I generate a Git patch for a specific commit?

I need to write a script that creates patches for a list of SHA-1 commit numbers.

I tried using git format-patch <the SHA1>, but that generated a patch for each commit since that SHA-1 value. After a few hundred patches were generated, I had to kill the process.

Is there a way to generate a patch only for the specific SHA-1 value?


Try:

git format-patch -1 <sha>

or

git format-patch -1 HEAD

According to the documentation link above, the -1 flag tells Git how many commits should be included in the patch;

-<n>

     Prepare patches from the topmost commits.


Apply the patch with the command:

git am < file.patch

For generating the patches from the topmost <n> commits from a specific SHA-1 hash:

git format-patch -<n> <SHA-1>

The last 10 patches from head in a single patch file:

git format-patch -10 HEAD --stdout > 0001-last-10-commits.patch

Say you have commit id 2 after commit 1 you would be able to run:

git diff 2 1 > mypatch.diff

where 2 and 1 are SHA-1 hashes.


This command (as suggested already by @Naftuli Tzvi Kay),

git format-patch -1 HEAD

Replace HEAD with a specific hash or range.

will generate the patch file for the latest commit formatted to resemble the Unix mailbox format.

-<n> - Prepare patches from the topmost <n> commits.

Then you can reapply the patch file in a mailbox format by:

git am -3k 001*.patch

See: man git-format-patch.