patch

apply a diff file to an original

Syntax

patch [options] [originalfile [patchfile]]

but usually just

patch -pnum <patchfile

Description

patch takes a patch file patchfile containing a difference listing produced by the diff program and applies those differences to one or more original files, producing patched versions. Normally the patched versions are put in place of the originals. Backups can be made.

Options

-b  or  --backup
       Make backup files. That is, when patching a file, rename or copy the original instead of removing it.

--binary
       Write all files in binary mode, except for standard output and /dev/tty.

-f  or  --force
       Assume that the user knows exactly what he or she is doing, and do not ask any questions.

-R  or  --reverse
       Assume that this patch was created with the old and new files swapped.

Example 1

Demonstrate patch command.

[eleiss@eleiss ~]$ cat hello-1.c
#include<stdio.h>

int main()
{
	printf("Hello");
	return 0;
}
[eleiss@eleiss ~]$ cat hello-1.1.c 
#include<stdio.h>

int main()
{
	printf("Hello World");
	printf("This is the updated version of this program");
	return 0;
}
[eleiss@eleiss ~]$ diff hello-1.c hello-1.1.c > hello-1.1.c.patch 
[eleiss@eleiss ~]$ cat hello-1.1.c.patch
5c5,6
< 	printf("Hello");
---
> 	printf("Hello World");
> 	printf("This is the updated version of this program");
[eleiss@eleiss ~]$ patch hello-1.c -b hello-1.1.c.patch
patching file hello-1.c
[eleiss@eleiss ~]$ cat hello-1.c
#include<stdio.h>

int main()
{
	printf("Hello World");
	printf("This is the updated version of this program");
	return 0;
}
[eleiss@eleiss ~]$ cat hello-1.c.orig 
#include<stdio.h>

int main()
{
	printf("Hello");
	return 0;
}
[eleiss@eleiss ~]$

In this example, two versions of a program file are displayed using cat command. The difference between the two versions is stored in a "patch" file using diff command.

Later, the lower version that is "hello-1.c" is patched using the patch command. But the original copy of the file is backed up using -b option.


You may write to resources@eleiss.com for any Linux related queries.

advertisement