Skip to content

Patch

Yes.., i forgot it again. I just don;t patch enough to make it stick. So here is a short guide again.

diff

To patch you first have to make a diff, for a single file it is easy. Here are two example files :

old:

original file
1
2
3
First line unmodified
Second line error
Third line superfluous

new:

changed file
1
2
3
Zero added
First line unmodified
Second line fixed

A simple diff old new gives :

human readable diff
1
2
3
4
5
6
7
0a1
> Zero added
2,3c3
< Second line error
< Third line superfluous
---
> Second line fixed

But that's way too human readable, so make a unified diff : diff -u old new

unified diff
1
2
3
4
5
6
7
8
-- old  2014-12-09 14:45:01.000000000 +0100
+++ new 2014-12-09 14:44:27.000000000 +0100
@@ -1,3 +1,3 @@
+Zero added
 First line unmodified
-Second line error
-Third line superfluous
+Second line fixed

Of course redirection would be your tool :

and save that in a patch file
diff -u old new > my.patch

This last format can be used for patch, see next chapter:

apply patch

To apply a patch, you normally have the file old , and the patch and want : new.

apply a patch
    patch < my.patch
No filenames needed, because they are in the patch file themselves, this command will turn old into new :

compare both
cmp old new

returns nothing. If you need to use a file that is named differently :

use a file not mentioned in the patch
    patch otherfile < my.patch

As you might have guessed 'new' is not used in any of these commands.

directories

On the diff side, this is easy, use the -r (recursive) option. But you need to diff something, so you need to have the original directory besides the altered one. A simple complete example:

recurse directory
mkdir old
echo "Hallo" >> old/file
cp -r old new
echo "extra regel" >> new/file
diff -ruN > dir.patch
-r (recursive), -u(unified) and -N means treat absent files as empty.

The patch file will contain :

patch content
1
2
3
4
5
6
diff -ruN old/file new/file
--- old/file    2014-12-09 15:33:24.000000000 +0100
+++ new/file    2014-12-09 15:33:59.000000000 +0100
@@ -1 +1,2 @@
 Hallo
+extra regel

Patching is done with :

patch apply patch
patch -p0 < dir.patch 

The -pX (--strip=X) is mandatory, and means strip X parts from the path prefix. So the -p0 would do nothing but :

depth
1
2
3
-p0 uses old/file
-p1 would use file
-p2 .. etc

git

Making patches with git is rather easy if you use the git commands both ways :

create git patch
git diff > my.patch

This produces unified format diff, but with some extra baggage, like a/ and b/ before the filenames. You could 'patch' that away again with -p1, or use

skip prefix
git diff --no-prefix

If you need to provide a 'patch' input. But the easiest is to use git again to 'apply' the patch ;

apply a patch
git apply my.patch