$linuxjunkies
>

patch(1)

Apply a unified diff patch file to one or more source files.

UbuntuDebianFedoraArch

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

FlagWhat it does
-p NUMStrip NUM leading path components from filenames in the patch (e.g., -p1 strips a/ prefix)
-i PATCHFILERead the patch from PATCHFILE instead of standard input
-o OUTFILEWrite the patched output to OUTFILE instead of modifying the original
-bBackup the original file before applying changes (creates .orig file)
--no-backup-if-mismatchDo not create backup files if the patch does not match perfectly
-NSkip files that are already patched (ignore if patch file not found)
-r REJECTFILEWrite rejected hunks to REJECTFILE instead of .rej file
--dry-runTest application of the patch without actually modifying files
-RReverse the sense of the patch (apply a removal as an addition, and vice versa)
-sSilent mode; do not print informational messages
-lIgnore whitespace changes when determining if lines match
--fuzz NUMAllow 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.patch

Apply patch with one leading path component stripped (common for patches generated with git or tar archives)

patch -p1 < changes.diff

Apply patch from security.patch file and create .orig backups of modified files

patch -i security.patch -b

Apply patch specifically to main.c, stripping no path components

patch -p0 main.c < bugfix.diff

Test whether the patch applies cleanly without making any actual changes

patch --dry-run -p1 < experimental.patch

Reverse/undo a previously applied patch

patch -R -p1 < feature.patch

Apply patch while ignoring whitespace differences (useful for reformatted code)

patch -p1 -l < indent-changes.diff

Apply patch and write result to patched-file.c instead of modifying the original

patch -p1 -o patched-file.c < changes.patch

Related commands