Website Vidya
Cloud & DevOpsStep-by-Step Guide

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.

RR
Rajesh RayLead Systems Educator
Published:
10 min read
PDF Cheat Sheet
Linux patch Command: Apply Diff Files & Source Patches
AI Executive SummaryWebsiteVidya AI

10 min read

Learn patch command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What patch Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

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.

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.

Advertisement
Linux patch Command: Apply Diff Files & Source Patches — syntax, flags, and practical terminal workflow diagram
Linux patch Command: Apply Diff Files & Source Patches — command syntax, key options, and production workflow reference.

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:

Advertisement

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 / FlagLong Form / ArgumentTechnical Behavior and Purpose
-p<num>--strip=<num>Strips <num> leading slashes and directory components from file paths in the patch header.
-R--reverseReverses the patch, swapping additions and deletions to undo previously applied changes.
--dry-run--dry-runSimulates patch execution without writing any changes to disk, reporting potential conflicts.
-b--backupCreates 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--forwardIgnores patches that appear to already be applied rather than attempting to re-apply or reverse them.
-l--ignore-whitespaceApplies 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--unifiedForces 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.

Advertisement

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

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

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
The -p1 option tells patch to strip off the first leading slash and preceding directory name from the file paths specified in the patch header. For example, if a diff header lists '--- a/src/app.py', passing -p1 removes 'a/' so patch looks for 'src/app.py' in the current working directory.
The patch command is a generic Unix tool that operates on any plain text files without requiring a Git repository. In contrast, git apply is integrated into Git, understands index metadata, binary diffs, and git submodules, and refuses to apply patches unless the entire working tree is cleanly applicable.
Use diff with the unified format (-u) or unified recursive options: diff -u original.txt modified.txt > change.patch. For entire directories, run diff -uNr original_dir/ modified_dir/ > project.patch.
When patch tries to apply a hunk and the context lines surrounding the modification do not match identically, it can ignore some trailing and leading context lines to make a best-effort match. The number of ignored lines is the 'fuzz factor'. A higher fuzz factor increases the risk of applying changes to the wrong location.
RR
Written byVerified Author

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.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Cloud & DevOps•

How to Close File Descriptors Above 9 in Dash Shell

Attempting to close a file descriptor above 9 in Dash using exec 10<&- results in a 10: not found error because Dash's POSIX lexer only recognizes single-digit file descriptors (0–9) in redirection operators. This guide explains the exact parser limitation, why FDs 10+ are reserved for internal shell state, and how to safely close inherited file descriptors using close_range, Python, or Perl wrappers.

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout