Generate and Apply patch in linux using diff and patch commands

Generate patch file:

Patch file says the difference between the existing version and the ‘patched’ version of the file.

Once you have edited the source you can create patch file using diff command…

I normally use below syntax of “diff” for creating a patch file..

#diff -Naur “original file” “modified version”

for ex: suppose u have below file in the system..

[terminal]
[root@humbles-lap patch]# cat main_orig.c
# include <stdio.h>

int main ()
{
printf (“\n I am original source \n”);
}

[root@humbles-lap patch]# cat main.c
# include <stdio.h>

int main ()
{
printf (“\n I am patched source \n”);
}

[root@humbles-lap patch]# diff -Naur main_orig.c main.c
— main_orig.c 2012-07-19 01:48:26.195898607 +0530
+++ main.c 2012-07-19 01:48:37.497899155 +0530
@@ -2,5 +2,5 @@

int main ()
{
– printf (“\n I am original source \n”);
+ printf (“\n I am patched source \n”);
}
[root@humbles-lap patch]#
[/terminal]
As this is an example, I used diff against different files “main_orig.c” and “main.c”, don’t get confused with that .. 🙂

“-” and “+” signs tell you which line is removed and which is added in its place..

How to apply a patch in a Linux system.

To apply a patch, you can use the “patch” command.

#patch -p1 <“patch file”

ex:
[terminal]
#patch -p1 < main.patch
[/terminal]
“-pnum” option controls how file names found in the patch file are used/treated..

Refer #man patch file for more information on this..