Skip to content

git format-patch

git format-patch is a Git command used to generate patch files that represent the differences between commits^[600-developer-tools-git-git-patch-cherry-pick.md]. These files can be used to transfer changes between repositories or for code review^[600-developer-tools-git-git-patch-cherry-pick.md].

Syntax

Single Commit

To generate a patch for a specific single commit, use the -1 flag followed by the commit reference^[600-developer-tools-git-git-patch-cherry-pick.md].

git format-patch -1 <commit_hash>

Multiple Commits

Commits from HEAD

To generate patches for the n most recent commits starting from HEAD, use the -n flag^[600-developer-tools-git-git-patch-cherry-pick.md].

git format-patch -n <commit_hash>

Range of Commits

To generate patches for all commits within a specific range (inclusive), use the triple-dot syntax (...) between the starting and ending commit hashes^[600-developer-tools-git-git-patch-cherry-pick.md].

git format-patch <start_commit>...<end_commit>

You can use the -o flag to specify an output directory for the patch files^[600-developer-tools-git-git-patch-cherry-pick.md].

Commits Since a Specific Change

To generate patches for all commits made after a specific commit (excluding that commit itself), simply provide the commit hash^[600-developer-tools-git-git-patch-cherry-pick.md].

git format-patch <commit_hash>

Applying Patches

Once generated, patch files can be applied to a target Git repository.

  1. Check statistics: Use git apply --stat <patch_file> to view a summary of the changes^[600-developer-tools-git-git-patch-cherry-pick.md].
  2. Check for errors: Use git apply --check <patch_file> to verify the patch can be applied cleanly^[600-developer-tools-git-git-patch-cherry-pick.md].
  3. Apply: Use git am to apply the patch as a commit^[600-developer-tools-git-git-patch-cherry-pick.md].

Sources

  • 600-developer-tools-git-git-patch-cherry-pick.md