patch - create, apply, reverse patches

Create a patch file

A patch file is a diff output file. It contains the name of the files that differed and the differences. To make one:

diff -u <unchanged file to patch> <file with changes> > <patch file>

-u is the ANT format

To view the patch contents:

cat <patch file>

Apply the patch file

Go to the directory where the file to patch is, then run:

patch <optional parameters> < <patch file>

Optional parameters:
-b makes a backup file of the patched files appended with .orig
-i <patch file> can be used instead of < <patch file>
-N skip the patch if already applied
-r- Do not create .rej files for rejected files - like for the patches which already are applied
--dry-run does not make the changes

If there are relative paths to files in sub directories in the path file use -p0 to use the full paths, use -p1 to ignore the first slash. Not using -pX will result in that patch ignores all paths and tries find and patch all mentioned files in the working directory.

No -pX:
/example/file is read as file
/example/file is read as /example/file
/example/file is read as example/file

On success the output can be:
patching file <old file>

On failure the output can be:
checking file <old file>
Hunk #1 FAILED at 1.
1 out of 1 hunk FAILED

If there are changes in the file close to the locations where the patch makes changes that differ from the patch, then you get fuzz notices when applying the patch. It warns that there are changes in the file to patch that did not match the contents in the patch, but the patch did not instruct to change these locations, so it proceeded anyway if it succeeded to patch.

Reverse patch

patch -R <file to be unpatched> < <patch file>

Create and apply patch for a directory tree with multiple files.

Create the patch:

diff -Nur <old-folder>/ <new-folder>/ > <patch file>

-N = treat absent files as new, -u = Use ANT format, -r = recursive

Apply the patch:

patch -p0 < <patch file>

-p0 = Use all paths as they are in the patch file. Without this patch will only use the file names without the paths and that will not work for a directory tree. If the paths in the patch file are absolute and you want to ignore the leading slashes use -p1 instead.


2011-11-02 18:46:59
2012-02-02 20:30:22
2022-02-17 14:16:25
2022-11-17 16:04:53

This is a personal note. Last updated: 2022-12-20 11:50:13.







Don't forget to pay my friend a visit too. Joakim