9.5 Applying a Patch

9.5 Applying a Patch

Every now and then, you might get a patch that you need to apply against source code to fix bugs or add features. You may also see the term diff used as a synonym for patch, because the diff program produces the patch.

The beginning of a patch looks something like this:

--- src/file.c.orig     2003-07-17 14:29:12.000000000 +0100
+++ src/file.c   2003-09-18 10:22:17.000000000 +0100
@@ -2,16 +2,12 @@

Patches usually contain alterations to more than one file. Search the patch for three dashes in a row (---) if you want to see the files that have alterations.

You should always look at the beginning of a patch to determine the required working directory. Notice that the preceding example refers to src/file.c. Therefore, you should change to the directory that contains src before applying the patch, not to the src directory itself.

To apply the patch, run the patch command:

patch -p0 < patch_file

If everything goes well, patch exits without a fuss, leaving you with an updated set of files. However, watch out if patch asks you this question:

File to patch:

This usually means that you are not in the correct directory. However, it could also indicate that your source code does not match the source code in the patch. In this case, you're probably out of luck — even if you could identify some of the files to patch, others would not be properly updated, leaving you with source code that you cannot compile.

In rare cases, you might come across a patch that refers to a package version like this:

--- package-3.42/src/file.c.orig     2003-07-17 14:29:12.000000000 +0100
+++ package-3.42/src/file.c   2003-09-18 10:22:17.000000000 +0100

If you have a slightly different version number (or you just renamed the directory), you can tell patch to strip leading path components. Let's say that you were in the directory that contains src (as before). To make patch ignore the package-3.42/ part of the path (that is, to strip one leading path component), use -p1:

patch -p1 < patch_file