How to create a patch file in Linux using diff command
In Category Command Line
Patch files describe the differences between two versions of same project and it is the favourite way of exchanging differences among developers. Patch files come in handy when the project is huge and exchanging whole source code is not so convenient. If you observe the download section of open source projects like Linux kernel, you will find patches for other versions based on a base version. That means if I had already downloaded sources of 2.6.0 version kernel sources and if I want 2.6.1 sources, I would rather download the patch file instead of downloading whole 2.6.1 source code.
Any Linux or UNIX system comes with “diff” and “patch” commands of which “diff” command is used to generate a patch and “patch” command is used to apply the patch.
Creating a patch file
Patch file creation requires original sources and modified sources. The following example assumes that the original sources are present in the directory “original” and the modified sources are present in “modified“.
[nick@techpulp ~]# ls original/ modified/ [nick@techpulp ~]# diff -Naur original modified > mychanges.patch
Testing the patch file
It is good to test the patch file before you publish and distribute it. But take backup of original sources before you attempt this. The “patch” command with “–dry-run” option can be used to validate the patch file without actually applying the patch.
[nick@techpulp ~]# cd original [nick@techpulp original]# patch -p1 --dry-run < ../mychanges.patch patching file CHANGES patching file Makefile patching file src/main.c [nick@techpulp original]#
Applying the patch
Applying patch is same as above but without “–dry-run” option.
[liz@techpulp ~]# cd original [liz@techpulp original]# patch -p1 < ../mychanges.patch patching file CHANGES patching file Makefile patching file src/main.c [liz@techpulp original]#
Another way of applying patch is to use “-i” option to specify the patch file.
[liz@techpulp ~]# cd original [liz@techpulp original]# patch -p1 -i ../mychanges.patch patching file CHANGES patching file Makefile patching file src/main.c [liz@techpulp original]#
Reversing a patch
You can remove an applied patch using “-R” option. This brings your patched sources to the original.
[liz@techpulp ~]# cd original [liz@techpulp original]# patch -p1 -R -i ../mychanges.patch
Recent Comments