Sometimes two repositories can’t reach each other, or you want to hand someone a few commits by mail or on a USB stick. git format-patch turns commits into files that keep everything.
git format-patch origin/main..HEAD -o patches/
Each commit in the range becomes one numbered file, like patches/0001-Add-export-button.patch. The file holds the diff plus the author, the date and the full message, in an email-like format. -1 exports only the last commit, and -3 the last three.
On the other side, git am turns them back into commits:
git am -3 patches/*.patch
The commits keep the original author and message; only the committer is the person who applied them. -3 lets git fall back to a three-way merge when the code has moved a little, which I think saves a lot of rejected patches.
That’s the big difference with git diff > file.patch: a plain diff has no commits in it, so you’d have to write the messages again.
If a patch doesn’t apply, git am stops in the middle. Fix the conflict, git add the files and run git am --continue, or give up with git am --abort. An empty commit can’t be exported this way either; git am stops at it with “Patch is empty”. Binary changes are included, but huge files make huge patches.
Further reading: git-format-patch documentation, git-am documentation