patch --dry-run: Test a Patch Before Applying
patch --dry-run runs all the checks of a real apply and reports the outcome, but writes nothing to disk.
A dry run is the safe way to validate a patch in CI: you learn whether every hunk applies before committing to editing files, so a failure does not leave a half-patched tree.
What it does
patch --dry-run parses the patch, locates each hunk in the target files, and prints what it would do (including "Hunk #N FAILED") without altering any file. The exit status is nonzero if any hunk would fail, so it doubles as a gate.
Common usage
# does it apply at all?
patch -p1 --dry-run < fix.patch && echo "clean"
# git equivalent for a git-format patch
git apply --check fix.patchOptions
| Flag / behavior | What it does |
|---|---|
| --dry-run | Report the result but write nothing |
| -p<n> | Strip level, same as a real apply |
| exit 0 | All hunks would apply cleanly |
| exit 1 | At least one hunk would fail |
| git apply --check | Equivalent dry check for git-generated patches |
In CI
Gate patch application on the dry run: patch -p1 --dry-run < p.patch (or git apply --check) as a required step, then apply for real only if it passes. This turns "the patch no longer applies to main" into a clear, early failure rather than a broken build later.
Common errors in CI
"Hunk #2 FAILED at 88" during a dry run means the surrounding lines drifted; the patch needs regenerating against current code. "can't find file to patch at input line 3" is a wrong -p level, not a content problem. Note git apply is stricter than patch and will reject fuzz that patch would accept, so the two can disagree on the same patch.