bashintermediate

Git Patch Create and Apply Workflow

Generate and apply git patches to share changes via email or transfer between repositories.

bash
# Create a patch from the last commit
git format-patch -1 HEAD
# Output: 0001-commit-message.patch

# Create patches for last N commits
git format-patch -3 HEAD

# Create patch from a range
git format-patch main..feature-branch

# Create a single combined patch file
git format-patch main..feature-branch --stdout > changes.patch

# Create diff patch (without commit metadata)
git diff > uncommitted.patch
git diff --staged > staged.patch
git diff main..feature-branch > branch.patch

# Check what a patch will do
git apply --check changes.patch

# Apply a diff patch
git apply changes.patch

# Apply format-patch (preserves commit info)
git am 0001-commit-message.patch

# Apply multiple patches in order
git am *.patch

# Apply with 3-way merge (handles conflicts better)
git am --3way 0001-commit-message.patch

# If apply fails, abort or resolve
git am --abort
# Or resolve conflicts, then:
git am --continue

# Create patch for specific file
git diff -- src/file.ts > file-changes.patch

Use Cases

  • Sharing changes without push access
  • Transferring commits between disconnected repos
  • Code review via email-based workflow

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.