patch

How to create a patch

Let's assume that we have the original tree under the directory ./hello-1.0 and want to modify it. First, we shuld make a copy of the sources,
cp -r hello-1.0 hello
which creates a new source tree under the directory ./hello. Now we do the changes to the code, and when we are happy with it, we want to create a patch file that incorporates our changes into the original tree.

We cd where the directories hello-1.0 and hello are, and do
diff -u -r hello-1.0 hello > hello.patch

The meaning of the options are

It is possible to create a patch for a single file. The first makes the diff between a file and the corresponding file in the second directory, the second between files with different filenames,
diff -u hello-1.0/hello.c hello > hello.patch
diff -u hello-1.0/hello.c hello/byebye.c > hello.patch

How to apply a patch

Let's assume that we have the original distribution tree, ./hello-1.0 and want to apply the patch hello.patch. First we create a copy of the original distribution,
cp -r hello-1.0 hello-1.1

Then we go into the new directory and applt the patch,
cd hello-1.1
patch -p1 < ../hello.patch

Sone of the options of patch are
  • -pN: skip N level of directories in the file names;
  • -b suffix: make a backup of the original with ".suffix";
  • -d dir: cd to "dir" before patching;
  • -n: interpret patch file as a normal diff;
  • -u: interpret patch file as unified context diff;
  • -R: try to do a reverse patch, ie, get the original file from the patched file. This is also useful who created the patch, interchanged the original and the modified.

Exercise

  1. Make a simple project in the directory hello-1.0 containing a C file "hello.c" and its makefile;
  2. Copy this project into another directory, say hello;
  3. Go to the parent directory and make a patch, hello.patch;
  4. Now copy the original into a new directory hello-1.1, and apply the patch. Verify the result.

Here is a solution to this exercise: hello.tgz


Marco Corvi - 2003