How to create and apply patch in Linux



Patch in Linux : 

A patch is piece of code used to adding new features, or fixing bugs, or adding documentation to the project. Patch is simple text file contains difference between two version of the same file. Before applying patch to your project always take a backup.Patch is generally for open source contribution.


Steps to create and apply patch for single file:

Write a simple c program for addition. But problem in the program is instead  of addition it subtract the number and print output as addition.
add.c
#include<stdio.h>
int main(){
 int a=10,b=20;
 int sum=0; 
 sum = a - b;
 printf("add = %d\n",sum);
 return 0;
}
----------------------------------
kb@kb :~$./a.out
add = -10
Now, copy the add.c to add_new.c
kb@kb:~$ cp add.c add_new.c
Edit the add_new.c as below:
#include<stdio.h>
int main(){
 int a=10,b=20;
 int sum=0; 
 sum = a + b;
 printf("add = %d\n",sum);
 return 0;
}
------------------------
kb@kb :~$ ./a.out
add = 30
create the patch file using diff command:
kb@kb:~$ diff -u add.c add_new.c > add.patch
Patch file: add.patch
--- add.c 2015-12-28 15:34:53.391145542 +0530
+++ add_new.c 2015-12-28 15:34:50.459145384 +0530
@@ -2,7 +2,7 @@
 int main(){
  int a=10,b=20;
  int sum=0; 
- sum = a - b;
+ sum = a + b;
  printf("add = %d\n",sum);
  return 0;
 }
- in the code means this line is removed. + in the code means this line is added. 
Now apply patch to original source code: add.c
$ patch < add.patch
patching file add.c 
Now both file add.c and add.patch contains the same code.
In next post we will learn how to apply patch to source code tree.

1 comments:

Post a Comment