Recently I changed something in an open source project and wanted to make the patch public.
It had been a long time since I made a patch, so I forgot how(even though it’s fairly easy).
So here’s a quick how-to.
Make sure you have both the original and modified versions.
In the example I’ll make a patch for a directory that contains 1 file with a few lines:
cd /tmp/ mkdir Source Source_new echo -e "a\nb\nc\nf\ng" > Source/file.txt echo -e "a\nb\nc\nd\ne\nf\ng" > Source_new/file.txt
Lets first see what all the changes are by running the following command:
diff -crBN Source Source_new
This command has a few options:
- ‘c’ : stands for ‘context output format’
- ‘r’: causes the diff to happen recursively
- ‘B’: makes sure we ignore blank line changes
- ‘N’: includes new files, by default new files will not be included in the patch
This is the output generated:
[root@host tmp]# diff -crBN Source Source_new diff -crBN Source/file.txt Source_new/file.txt *** Source/file.txt 2011-08-14 15:30:39.000000000 -0500 --- Source_new/file.txt 2011-08-14 15:30:39.000000000 -0500 *************** *** 1,5 **** --- 1,7 ---- a b c + d + e f g
It’s best to go over all the changes and delete those that are not needed. A patch should be as small as possible to avoid issues when the original software has updates etc.
To save the patch, simply redirect the output to a file:
diff -crBN Source Source_new > mychanges.patch
Now you have a usable patch.
The next step is to try and apply it on the original version.
First run a dry run by doing the following:
patch --dry-run -p1 -i /tmp/mychanges.patch -d /tmp/Source
Your output should be like this:
[root@host tmp]# patch --dry-run -p1 -i /tmp/mychanges.patch -d /tmp/Source patching file file.txt
To apply the patch for real, run it without the –dry-run:
patch -p1 -i /tmp/mychanges.patch -d /tmp/Source
So that’s how to create and apply a patch