Linux patch Command: Apply Diff Files & Source Patches
Learn patch command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
10 min read
Learn patch command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What patch Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
Software maintenance, kernel compilation, and open-source collaboration rely fundamentally on the patch command in linux to distribute and apply incremental source code updates without transmitting full file archives. Authored originally by Larry Wall and maintained under the GNU Project, patch reads diff output files and modifies text files line by line with surgical precision.
The patch command in Linux takes patch or diff files produced by the diff utility and applies the modifications directly to one or more original files. Run patch -p1 < update.patch inside a repository or project root to apply unified diffs, or use patch --dry-run to test whether a patch applies cleanly before modifying any files.
Before distributed version control systems like Git became ubiquitous, developers shared patches via mailing lists and bug trackers as unified diffs. Even today, Linux distribution package maintainers (for Debian, RPM, and Arch PKGBUILDs), embedded firmware builders, and automated deployment pipelines use patch to inject distribution-specific hotfixes, backport security CVE patches, and customize upstream software during compilation.
In this guide, we analyze the internal hunk-matching engine of patch, demonstrate path-stripping mechanics, review essential command options, explore practical examples, and review disaster recovery practices for handling rejected hunks.
What patch Does and When to Use It
Internally, patch parses diff formats—primarily Unified diffs (indicated by --- and +++ headers) and Context diffs (indicated by *** and --- headers). The diff file breaks modifications into discrete logical units called 'hunks'. Each hunk begins with line-number range coordinates (e.g., @@ -42,7 +42,9 @@) followed by leading context lines, deleted lines prefixed with minus (-), added lines prefixed with plus (+), and trailing context lines.
When applying a hunk, patch does not require exact line number matching. If preceding edits have shifted file line numbers, patch calculates a line offset. If the context lines nearby have slightly changed, patch applies a 'fuzz factor' (matching fewer context lines). However, if the context cannot be resolved unambiguously, patch aborts the hunk, leaves the original file untouched at that location, and writes the failing hunk to a reject file ending in .rej while preserving a backup of the original in .orig.
Under the hood, patch gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -p<num>, -R, --dry-run, -b turns raw process and service tables into actionable diagnostics during incident response.
Availability and Installation Across Linux Distributions
The patch utility is packaged in patch across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether patch is installed and inspect which binary path and version your shell resolves:
type -a patch
patch --version 2>/dev/null || man -f patch
# Illustrative output (reviewed against documentation)
patch is /usr/bin/patch
patch (patch)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y patch
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y patch
# Arch Linux
sudo pacman -S --noconfirm patch
# Alpine Linux
sudo apk add --no-cache patch
Command Syntax, Arguments, and Exit Status Codes
patch [OPTIONS] [ORIGINALFILE [PATCHFILE]]
The standard invocation syntax is patch [OPTIONS] [ORIGINALFILE [PATCHFILE]]. In standard Unix workflows, patch reads the patch file from standard input via shell redirection (e.g., patch -p1 < fix.patch) or takes the patch file as an explicit argument with -i fix.patch. If the patch file contains header paths (such as a/src/main.c and b/src/main.c), patch automatically identifies target files relative to the current working directory.
The most vital argument to understand is the strip level specified by -p<number> (or --strip). In unified diffs generated by Git or diff -uNr, paths often contain artificial directory prefixes (e.g., a/ or b/). Passing -p1 instructs patch to strip off the first leading slash and preceding directory component, matching local file paths accurately. Passing -p0 preserves the path unchanged.
0— All hunks applied successfully without any rejections.1— Some hunks could not be applied and were dumped to .rej files.2— Severe operational failure, such as missing patch file, memory allocation error, or corrupt diff syntax.130— Process interrupted by user signal (SIGINT, Ctrl+C).
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-p<num> | --strip=<num> | Strips <num> leading slashes and directory components from file paths in the patch header. |
-R | --reverse | Reverses the patch, swapping additions and deletions to undo previously applied changes. |
--dry-run | --dry-run | Simulates patch execution without writing any changes to disk, reporting potential conflicts. |
-b | --backup | Creates backup copies of original files before modifying them (default suffix is .orig). |
--suffix=<sfx> | --suffix=<sfx> | Specifies a custom backup extension suffix instead of the default .orig. |
-N | --forward | Ignores patches that appear to already be applied rather than attempting to re-apply or reverse them. |
-l | --ignore-whitespace | Applies hunks loosely by ignoring differences in space and tab indentation. |
-r <file> | --reject-file=<file> | Specifies a custom output path for rejected hunks instead of target.rej. |
-u | --unified | Forces patch to interpret the patch file strictly as a unified diff format. |
Using --dry-run before applying third-party patches is considered an essential best practice. It verifies whether your local source tree matches the baseline code that the patch author branched from, alerting you to hunks that would fail or generate .rej files before any on-disk files are touched.
When integrating patches into automated build environments (such as Dockerfiles or CI/CD pipelines), combining -p1 with -N (forward) and --batch prevents patch from prompting interactively if a hunk encounters unexpected ambiguities, ensuring scripts terminate with a clear non-zero exit code on failure.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Apply a Unified Diff Patch via Standard Input
Apply a simple diff file to a local source file in the current directory using shell redirection.
patch < bugfix.patch
# Illustrative output (reviewed against documentation)
patching file config.py
Hunk #1 succeeded at 18 (offset 2 lines).
The patch utility reads the diff from standard input, identifies config.py from the patch header, calculates a 2-line offset, and modifies the file in place.
2. Strip Leading Path Components with -p1 in Git Repositories
Apply a patch generated by git diff or git format-patch by stripping the leading a/ and b/ path prefixes.
patch -p1 < 0001-fix-database-connection-timeout.patch
# Illustrative output (reviewed against documentation)
patching file src/database/connector.py
patching file tests/test_connector.py
Because git diff prepends a/ and b/ to file paths, -p1 removes the first directory segment so that src/database/connector.py matches the local repository directory layout.
3. Simulate Patch Application with --dry-run
Verify that a patch applies cleanly against the current codebase without altering any files on disk.
patch -p1 --dry-run < vendor-security-update.patch
# Illustrative output (reviewed against documentation)
checking file lib/auth/jwt.c
checking file lib/auth/tokens.c
The --dry-run option validates all hunk headers and context lines against existing files, ensuring zero changes are committed until you run the command without --dry-run.
4. Reverse an Applied Patch to Revert Code Changes
Undo a previously applied patch by swapping additions and deletions using the -R (reverse) flag.
patch -p1 -R < 0001-fix-database-connection-timeout.patch
# Illustrative output (reviewed against documentation)
patching file src/database/connector.py
patching file tests/test_connector.py
The -R option treats plus signs as deletions and minus signs as additions, restoring the original source code back to its pre-patch state.
5. Create Automatic Backup Copies with Custom Suffixes
Instruct patch to save backups of every modified file before overwriting them.
patch -p1 -b --suffix=.bak < performance-tune.patch
# Illustrative output (reviewed against documentation)
patching file src/core/engine.cpp
# Backup saved to src/core/engine.cpp.bak
The -b flag creates a backup file, and --suffix=.bak overrides the default .orig suffix, preserving original copies for auditing.
6. Ignore Whitespace and Indentation Differences
Apply a patch when upstream formatting or tab-versus-space indentation differs slightly between file versions.
patch -p1 -l < style-fix.patch
# Illustrative output (reviewed against documentation)
patching file app/views.py
Hunk #1 succeeded at 45 with fuzz 1.
The -l (or --ignore-whitespace) option treats sequences of consecutive spaces and tabs as equivalent, preventing hunks from failing solely due to indentation changes.
Real-World Workflows, Pipelines, and Shell Automation
Emergency Hotfix Ingestion Pipeline in CI/CD Builds
Automatically test and apply vendor security patches during containerized software builds, failing immediately on conflicts.
#!/usr/bin/env bash
set -euo pipefail
PATCH_FILE="patches/CVE-2026-9912.patch"
echo "[CI] Validating patch integrity: $PATCH_FILE"
if patch -p1 --dry-run --batch -s < "$PATCH_FILE"; then
echo "[CI] Applying patch cleanly..."
patch -p1 --batch -b < "$PATCH_FILE"
echo "[CI] Hotfix applied successfully."
else
echo "[FATAL] Patch conflict detected! Aborting build."
exit 1
fi
# Illustrative output (reviewed against documentation)
[CI] Validating patch integrity: patches/CVE-2026-9912.patch
[CI] Applying patch cleanly...
patching file server/protocols/http2.c
[CI] Hotfix applied successfully.
Combining --dry-run, --batch (non-interactive), and -s (silent) ensures unattended automated builds never stall at user prompts and halt cleanly if conflicts arise.
Inspecting and Resolving Rejected Hunks (.rej Files)
When a patch partially fails, locate and inspect .rej files to manually port conflicting changes.
patch -p1 < feature.patch || true
find . -name "*.rej" -print
cat src/routes.py.rej
# Illustrative output (reviewed against documentation)
patching file src/routes.py
Hunk #2 FAILED at 64.
1 out of 2 hunks FAILED -- saving rejects to file src/routes.py.rej
./src/routes.py.rej
--- src/routes.py
+++ src/routes.py
@@ -64,5 +64,6 @@
- @app.route('/login')
+ @app.route('/v1/login')
Examining the .rej file shows the exact lines that could not be matched, allowing developers to manually integrate the code into the target file before deleting the reject file.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding patch inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
Applying a malformed or mismatched patch directly to production configuration or source files can corrupt line numbering and introduce syntax bugs. Always create backups (-b) or test first with --dry-run before committing modifications.
Exercise extreme caution when downloading and applying patches from untrusted sources. Historically, vulnerabilities in older patch implementations (such as CVE-2018-20969 and CVE-2019-13638) allowed maliciously crafted diff files to escape directory hierarchies through directory traversal (e.g., ../../../etc/shadow) or shell command execution in certain wrapper tools.
Modern versions of GNU patch enforce directory boundaries, but as a standard security protocol, always inspect patch files with a text viewer or git apply --check before piping them into privileged processes. Ensure patch execution runs under an unprivileged build account rather than root.
GNU/Linux, BSD, and BusyBox Implementation Differences
GNU patch (standard on Debian, Ubuntu, RHEL, Fedora, and Arch) provides rich extensions including --dry-run, --backup-if-mismatch, and advanced fuzz factor controls. BSD patch (used on FreeBSD, NetBSD, and macOS) supports basic POSIX syntax and -p<num>, but may lack certain long-form GNU flags.
On BusyBox systems (common in minimal Alpine or embedded environments), the built-in patch applet is stripped down. It supports -p, -R, and -i, but lacks --dry-run, --suffix, and verbose diagnostics. For complex multi-file patches on Alpine Linux, installing the full gnu-patch package (apk add patch) is required.
Troubleshooting Common Errors and Diagnostics
1 out of X hunks FAILED -- saving rejects to file
Root Cause: The target file has changed significantly since the patch was created, causing the context lines in the diff to fail matching.
Resolution: Inspect the generated .rej file to see the rejected lines, manually merge the changes into the target file, and remove the .rej file.
cat file.py.rej
# Manually edit file.py, then remove reject:
rm file.py.rej
Reversed (or previously applied) patch detected! Assume -R? [n]
Root Cause: You ran patch on a file that already has the modifications applied, or the patch was generated in reverse.
Resolution: Answer 'n' to abort if the patch is already applied, or use -N (--forward) in automated scripts to ignore already-applied patches.
patch -p1 -N < update.patch
can't find file to patch at input line X
Root Cause: The strip level (-p) does not match the directory layout, or the file does not exist in the working directory.
Resolution: Check the header of the patch file to inspect file paths, and supply the correct -p level (usually -p1 for git diffs or -p0 for local diffs).
head -n 5 update.patch
patch -p1 < update.patch
Alternatives, Related Commands, and Related Tutorials
- chown Command in Linux: Change File & Directory Ownership — Practical syntax, flags, and examples for
chown. - mkdir Command in Linux: Create Directories & Parent Trees — Practical syntax, flags, and examples for
mkdir. - rename Command in Linux: Batch Rename Files with Regex — Practical syntax, flags, and examples for
rename. - git fetch vs git pull: Key Differences, Workflows & Examples — Practical syntax, flags, and examples for
git. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides



Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!