patch(1)
Apply a unified diff patch file to one or more source files.
Synopsis
patch [OPTION]... [ORIGFILE [PATCHFILE]]Description
patch reads a patch file (usually generated by diff -u) and applies the changes to one or more original files. It can handle unified diffs, context diffs, and normal diffs. patch is essential for applying source code updates, security fixes, and collaborative development patches.
If ORIGFILE is not specified, patch attempts to determine the filename from the patch header. If PATCHFILE is not given, patch reads from standard input. patch creates backups of modified files by default (with .orig extension) and reports statistics on successful and failed hunks.
Common options
| Flag | What it does |
|---|---|
-p NUM | Strip NUM leading path components from filenames in the patch (e.g., -p1 strips a/ prefix) |
-i PATCHFILE | Read the patch from PATCHFILE instead of standard input |
-o OUTFILE | Write the patched output to OUTFILE instead of modifying the original |
-b | Backup the original file before applying changes (creates .orig file) |
--no-backup-if-mismatch | Do not create backup files if the patch does not match perfectly |
-N | Skip files that are already patched (ignore if patch file not found) |
-r REJECTFILE | Write rejected hunks to REJECTFILE instead of .rej file |
--dry-run | Test application of the patch without actually modifying files |
-R | Reverse the sense of the patch (apply a removal as an addition, and vice versa) |
-s | Silent mode; do not print informational messages |
-l | Ignore whitespace changes when determining if lines match |
--fuzz NUM | Allow fuzzy matching with up to NUM lines of context deviation |
Examples
Apply patch from standard input to files specified in the patch header
patch < fix.patchApply patch with one leading path component stripped (common for patches generated with git or tar archives)
patch -p1 < changes.diffApply patch from security.patch file and create .orig backups of modified files
patch -i security.patch -bApply patch specifically to main.c, stripping no path components
patch -p0 main.c < bugfix.diffTest whether the patch applies cleanly without making any actual changes
patch --dry-run -p1 < experimental.patchReverse/undo a previously applied patch
patch -R -p1 < feature.patchApply patch while ignoring whitespace differences (useful for reformatted code)
patch -p1 -l < indent-changes.diffApply patch and write result to patched-file.c instead of modifying the original
patch -p1 -o patched-file.c < changes.patch