Patch (Application)

From LQWiki
Jump to navigation Jump to search

The application patch takes a sourcecode file (or any other file for that matter) and a diff file based on changes that have been made to another copy of the source. It then merges the two, applying the changes specified to the source file. This is particularly useful for allowing developers to collaborate through CVS repositories.

Patch only has a small job, but it is hard to have it do this. So, some syntax examples are needed. Here they are:

We create two versions of a file:

$ cat >file1
hello
world
greetings
mars
hi
moon
$ cat >file2
hello
world
greetings
mars
howdy
moon

We show the resulting patch:

$ diff -up file1 file2
--- file1       2007-07-05 22:13:42.000000000 +0200
+++ file2       2007-07-05 22:13:51.000000000 +0200
@@ -2,5 +2,5 @@ hello
 world
 greetings
 mars
-hi
+howdy
 moon

Note that the patch only shows the difference between the two files. The line "hi" is subtracted:

-hi

instead, a line "howdy" is added:

+howdy

It is best practice to store the patch in a file:

diff -up file1 file2 > file1_file2.diff

Now, although file1_file2.diff contains all information, patch file1_file2.diff will fail. Instead, to patch file1, you will have to:

$ patch file1 <file1_file2.diff
patching file file1
$ cat file1
hello
world
greetings
mars
howdy
moon
$