Applying a patch is a fundamental developer skill. It’s about using a text file that outlines code changes often called a diff to update your local codebase. The most common ways to do this are with command-line tools like git apply for Git repositories or the classic patch utility for any directory. Getting this right means you can integrate fixes, share code, and collaborate in ways that go beyond a simple pull request.
TL;DR: How to Apply a Patch
- For Git Repos: Use
git apply path/to/patch.diffto apply changes to your working directory without creating a commit. This lets you test the changes first. - For Email-Based Patches: Use
git am < patch.emlto apply a patch from an email, which automatically creates a commit and preserves the original author’s info. - Outside of Git: Use the classic
patch < my_patch.patchcommand. If paths don’t match,patch -p1 < my_patch.patchusually fixes it. - Handling Failures: If a patch fails, look for
.rejfiles. These files contain the changes that couldn’t be applied, which you’ll need to add manually. - After Applying: Always run your full test suite, conduct a quick code review, and update relevant documentation to ensure the patch didn’t introduce new problems.
Table of Contents
What Exactly Is a Patch and Why Does It Matter?
Before diving into commands, let’s clarify what a patch is. A patch is a text file containing instructions on how to turn one version of a file (or many files) into another.
The patch file is created by comparing two code versions, but it only records the lines that were added, removed, or changed. Think of it as a precise, surgical recipe for an update.
In my experience, this simple concept is a cornerstone of collaborative software development and a lifesaver when a full git merge isn’t the right tool for the job.
The Real-World Power of Patches
Patches are incredibly versatile because they are self-contained. They solve modern development problems with an efficiency that’s hard to beat.
Here are a few situations where knowing how to handle a patch is invaluable:
- Open-Source Contributions: Many projects, especially older ones, manage contributions through mailing lists. If you want to learn how to contribute to open source projects, you’ll need to get comfortable with creating and applying patches sent via email.
- Limited Repository Access: Need to share a quick fix with a colleague who doesn’t have push access? Instead of messing with repository permissions, just send them a patch file.
- Integrating Upstream Fixes: When maintaining a fork, you often need to pull specific bug fixes from the original repository without merging entire branches. A patch lets you cherry-pick just the fix you need.
- Legacy System Maintenance: I’ve worked on older systems where a full merge feels risky. Applying a targeted patch is a much safer way to deploy a critical security update or bug fix.
In essence, a patch allows developers to share and apply changes in a controlled, isolated manner. It’s about precision making only the necessary edits without the overhead of a full branch merge, which is invaluable for maintaining stability and clarity in a codebase.
This approach keeps projects moving forward without adding unnecessary complexity.
How to Apply a Patch Using Git
If you’re in the Git ecosystem, you have powerful, native tools for handling patches. Knowing these commands gives you finer control over your codebase.
With remote teams, we’re dealing with a much higher volume of patches. It’s no surprise the global patch management market is projected to jump from USD 950.5 million to USD 2.25 billion by 2034.
Using git apply for Direct Patching
The most straightforward tool is git apply. It reads a patch file and applies the changes to your working directory.
The key difference: git apply does not create a commit. It just stages the changes, giving you a chance to review everything before finalizing. I find this useful for testing if a patch works before committing to it.
Before applying, do a dry run with the --check flag. It verifies if the patch will apply cleanly without touching your files.
git apply --check path/to/your/patch.diff
If that command runs silently, you’re good. If it shows errors, you have conflicts to sort out.
Once confident, apply it for real:
git apply path/to/your/patch.diff
Handling Patches That Don’t Apply Cleanly
What if a patch file has changes for multiple files, but only some apply cleanly? Use the --reject flag.
git apply --reject path/to/your/patch.diff
This command applies the clean parts and creates .rej (rejected) files for the parts that fail. These files contain the diff chunks that couldn’t be applied, which helps you resolve conflicts manually.
Applying Patches from GitHub Pull Requests
Here’s a trick I use often. Every GitHub pull request has a corresponding .patch file. Just add .patch to the end of the PR’s URL.
This lets you pull the changes and apply them from your terminal using curl and piping the output into git apply.
curl -L https://github.com/owner/repo/pull/123.patch | git apply
This is perfect for testing changes from a PR locally without checking out the entire branch.
The diagram below shows how a patch file is created from the differences between two code versions.

It’s a neat illustration of how the delta between Code v1 and Code v2 gets distilled into a single, portable file.
Using git am for Email-Based Workflows
While git apply is a general-purpose tool, git am (apply mail) is for applying patches sent via email, common in projects like the Linux kernel.
The big distinction is that git am creates a commit directly from the patch file. It parses the email, pulling the author, date, and commit message to preserve the original metadata.
Let’s say you’ve saved a patch from an email into a file named fix.eml. Applying it is simple:
git am < fix.eml
git am creates a new commit on your current branch with the original author’s info. Mastering these Git commands is key for effective source control practices.
The Classic patch Command: A Unix Staple
Before Git dominated, the patch command was the workhorse for sharing code changes. It’s a foundational Unix utility that’s still relevant, especially when working on code outside a Git repository.
I still use patch for legacy systems or applying a quick fix without initializing a repo.
The Basic Patch Workflow

The most straightforward way to use patch is to feed a patch file directly into the command.
Here’s the basic syntax:
patch < my_patch.patch
This command looks for the files named in my_patch.patch and applies the changes.
It can also easily reverse a change. If a patch introduced a bug, back it out with the --reverse (or -R) flag.
patch --reverse < my_patch.patch
This applies the changes in reverse, cleanly undoing the original operation.
Mastering Paths with the -p Flag
A common issue with patch is a path mismatch. This happens when a patch was created with file paths that don’t line up with your local directory structure.
The -p (or --strip) option solves this. It tells patch to ignore a certain number of leading directories from the file paths.
patch -p0 < my_patch.patch: Default. Expects the full path to match from your current directory.patch -p1 < my_patch.patch: Strips the first leading directory. A path likeproject/src/main.cbecomessrc/main.c.patch -p2 < my_patch.patch: Strips the first two directories, turningproject/src/main.cintomain.c.
In my experience, patch -p1 is what I use 90% of the time. It’s the most common fix needed to get a patch from someone else to apply cleanly.
A Complete End-to-End Example
Let’s walk through creating and applying a patch from scratch, outside of version control.
First, we need two versions of a file. Let’s create an original config.js and a modified config_new.js.
Now, generate the patch file using the diff command. The -u flag creates a “unified” diff format that patch understands.
diff -u config.js config_new.js > config.patch
This command compares the files and saves the differences into config.patch.
Finally, apply the change to the original file:
patch < config.patch
Your config.js file is now identical to config_new.js. For a broader guide to effectively using code from programming tutorials and other sources, that resource is a great next step.
Troubleshooting a Failed Patch Application
Patches don’t always apply cleanly. A patch can fail if the code it’s trying to change has drifted too far from the original version.
When a patch fails, your terminal gives you clues. Both git apply and patch tell you which parts, or “hunks,” couldn’t be applied.
What to Do with Rejected Hunks
The key to fixing a failed patch lies in the .rej files it creates. When a patch tool can’t match a hunk, it writes that chunk into a file with a .rej extension (short for “rejected”).
The .rej file is your roadmap for a manual fix. It contains the exact lines the patch wanted to change, helping you apply them by hand.
You might also see a .orig file, which is a backup of the original file before the patch was attempted.
The Manual Fix: A Step-By-Step Guide
Once you have a .rej file, the process is methodical.
Here’s how I tackle it:
- See what was rejected. Open the
.rejfile. You’ll see the diff format, with+for added lines and-for removed lines. - Edit the source file by hand. Open the target source file and compare it to the
.rejfile. Your job is to logically integrate the intended changes. - Clean up. After applying the changes and verifying your code works, delete the
.rejand.origfiles. This signals that the conflict is resolved.
For a deeper dive, check out this guide on resolving conflicts in Git.
Patch Application Tools Compared
Choosing the right tool makes a difference. Here’s a quick rundown.
| Tool | Primary Use Case | Key Feature | Conflict Handling |
|---|---|---|---|
git apply | Applying simple patches to a working directory without creating commits. | Checks if a patch will apply cleanly (--check) before making changes. | Fails on conflict, leaves .rej files. Does not modify original files. |
git am | Applying a series of patches from an email mailbox (.mbox) format. | Creates a separate commit for each patch, preserving the original author and commit message. | Stops on conflict, allowing you to resolve it and continue (--continue). |
patch | The classic Unix utility for applying patches created with diff. | Highly portable and universally available. Offers options for ignoring whitespace (-l). | Can be less precise; may apply parts of a patch and leave .rej and .orig files. |
| GitHub CLI | Applying a pull request directly from the command line. | gh pr checkout or gh pr diff | git apply for seamless PR integration. | Handled through standard Git merge/rebase conflict resolution tools. |
How to Avoid Conflicts in the First Place
While knowing how to fix a broken patch is critical, avoiding the problem is better.
The best proactive strategy is simple: sync your branch. Before applying a patch, make sure your local code is up-to-date with the branch the patch was based on. A
git pullcan often close the gap that would have caused a conflict.
This is critical in fast-moving projects. According to industry reports, 30–40% of organizations report delays in patch application because of compatibility concerns. These delays are risky, as over 60% of successful cyberattacks exploit known vulnerabilities for which a patch was available but not yet applied.
What to Do After a Patch Is Applied
Getting a patch to apply cleanly is just the starting line. In my experience, the real work begins now to ensure the patch didn’t silently break something.
Your post-application checklist is what separates a stable codebase from one that’s constantly putting out fires.

This process is a crucial part of a healthy development cycle, mirroring the checks in a solid continuous integration pipeline.
Run Your Entire Test Suite
First, run your tests. Not just a few related ones run the entire suite.
This step is non-negotiable. You’re answering two questions:
- Did it fix the problem? The tests related to the original bug should now pass.
- Did it break anything else? The rest of your test suite is designed to catch regressions.
Catching a regression now is far less stressful than finding it in production.
Conduct a Quick Code Review
Even if the patch came from a trusted source, a quick review is a good idea. You’re looking at how the patch integrated with the current codebase.
Here’s what I look for:
- Style and Formatting: Does the new code follow your project’s style guide?
- Security Concerns: Did the patch introduce any new vulnerabilities?
- Clarity and Readability: Is the new code easy to understand?
This review provides a final sanity check on the quality and safety of the change.
Update Your Documentation
This step is often skipped, and it’s where technical debt begins. Any patch that changes behavior can make your documentation instantly wrong.
Outdated documentation isn’t just a minor annoyance; it’s a bug. It misleads new developers, frustrates users, and slows down everyone.
A simple code patch can easily invalidate:
- READMEs: Installation steps or configuration examples might be incorrect.
- API Guides: A changed endpoint needs to be updated immediately.
- Onboarding Tutorials: New hires will be working with outdated instructions.
This is where continuous documentation becomes powerful. Instead of treating documentation as a manual chore, you can automate it. In our own workflow, we use a tool like DeepDocs for this. It plugs into GitHub and automatically detects when a code change makes your documentation stale. It then opens a pull request with the necessary updates, ensuring your docs and code never drift apart.
Frequently Asked Questions
Here are some of the most common questions that pop up when applying patches.
What’s the difference between git apply and git am?
This is a common point of confusion. The simplest way to think about it is that git apply just modifies your files, while git am actually creates new commits.
git apply: Use this to apply adiffto your working directory without creating a commit. I use this to test a patch locally before deciding to formally commit it.git am: This command reads patches from an email format (mbox). It creates a new commit for each patch, preserving the original author, date, and commit message. You’d usegit amwhen integrating contributions from a mailing list.
How do I create my own patch file?
Creating a patch file is a fundamental skill.
For Uncommitted Changes in Git: If you have edits in your working directory, use:
git diff > my_patch.patch.To Create a Patch from Commits: Use
git format-patch <commit-hash>. It bundles metadata like the author and commit message into the patch file. This is the professional way to share commits as patches.Outside of a Git Repository: Use the standard Unix utility:
diff -u old_file.txt new_file.txt > my_patch.patch.
What do I do with .rej and .orig files?
If you see .rej and .orig files after applying a patch, it means things didn’t go perfectly.
The .rej file contains the specific chunks from the patch that couldn’t be applied. This is your to-do list for fixing things manually. The .orig file is a backup of your file before the patch attempt.
Open the .rej file, see which lines failed, and then manually edit your source file to incorporate those changes. Once everything works, you can safely delete both the .rej and .orig files.
The pressure to resolve these issues quickly is real. Federal agencies sometimes have only 7–14 days to apply critical security patches. This has fueled automated tools, allowing organizations to patch 70–80% of endpoints within 15 days, a huge jump from the 40–50% in regions with manual processes. You can dig into these patch and remediation software market trends to see how automation is changing the game.
By the way, once you’ve patched the code, don’t forget the documentation. Keeping docs in sync is just as critical as testing the code itself. With DeepDocs, you can put this on autopilot. It watches for code changes and automatically updates your READMEs, API guides, and tutorials. Check it out at https://deepdocs.dev.

Leave a Reply