Softpanorama

Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
May the source be with you, but remember the KISS principle ;-)
Skepticism and critical thinking is not panacea, but can help to understand the world better

patch command

News

Recommended Books

Recommended Links

Reference

Program Understanding

Some implementations

patch wdiff dwdiff, kdiff3 tkdiff

pdiff

    Admin Horror Stories Unix History Humor Etc

patch is used with the output of diff, the so-called diffs between two items, to make selective changes. A typical use of patch is to update your copy of a program's source code or HTML file.

diff mypage_old.html mypage.html > mypage.html.patchfile

A patch file patchfile should contain a difference listing produced by the diff program. Normally the patched versions replace the original file. Backups can be made; see the -b or --backup option. The names of the files to be patched are usually taken from the patch file, but if there's just one file to be patched it can be specified on the command line as originalfile.

Upon startup, patch attempts to determine the type of the diff listing, unless overruled by a -c (--context), -e (--ed), -n (--normal), or -u (--unified) option. Context diffs (old-style, new-style, and unified) and normal diffs are applied by the patch program itself, while ed diffs are simply fed to the ed(1) editor via a pipe.

The most common operation is to apply patch file on a remote server. First you need to transfer the patch to the same directory where the page reside

Now we have an old file and a patch file in the same directory we can apply this patch file.

patch < myapp.patchfile

While taking backup there may be all ready an backup file. So we need to save multiple backup files without overwriting. There is -V option which will set the versioning mechanism of the original file. In this example we will use numbered versioning.

patch -b -V numbered < myapp.patch

Patches make sense only if  the code has changed very little

You can also create a diff for the whole directory, not just a single file.

To apply such a diffs the syntax is then

patch -p number < patch_name

The number depends on how deep the subdirectory lies below the current directory. A patch will generally include instructions for where to place it and what number to use.

To create a patch for the while subtree you can use the command:

diff -Naur old_tree new_tree 

where old and new identify the old and new root directories of trees that you want to patch

The names old and new should not contain any slashes, or you need to delete then using -p num option when applying the patch.

Selected Options

-d dir or --directory=dir
Change to the directory dir immediately, before doing anything else.
-i patchfile or --input=patchfile
Read the patch from patchfile. If patchfile is -, read from standard input, the default.
-l or --ignore-whitespace
Match patterns loosely, in case tabs or spaces have been munged in your files. Any sequence of one or more blanks in the patch file matches any sequence in the original file, and sequences of blanks at the ends of lines are ignored. Normal characters must still match exactly. Each line of the context must still match a line in the original file.
-n or --normal
Interpret the patch file as a normal diff.
-N or --forward
Ignore patches that seem to be reversed or already applied. See also -R.
-o outfile or --output=outfile
Send output to outfile instead of patching files in place. Do not use this option if outfile is one of the files to be patched. When outfile is -, send output to standard output, and send any messages that would usually go to standard output to standard error.
-p num or --strip=num
Strip the smallest prefix containing num leading slashes from each file name found in the patch file. A sequence of one or more adjacent slashes is counted as a single slash. This controls how file names found in the patch file are treated, in case you keep your files in a different directory than the person who sent out the patch. For example, supposing the file name in the patch file was

/u/howard/src/blurfl/blurfl.c

setting -p0 gives the entire file name unmodified, -p1 gives

u/howard/src/blurfl/blurfl.c

without the leading slash, -p4 gives

blurfl/blurfl.c

and not specifying -p at all just gives you blurfl.c. Whatever you end up with is looked for either in the current directory, or the directory specified by the -d option.

-t or --batch
Suppress questions like -f, but make some different assumptions: skip patches whose headers do not contain file names (the same as -f); skip patches for which the file has the wrong version for the Prereq: line in the patch; and assume that patches are reversed if they look like they are.
-T or --set-time
Set the modification and access times of patched files from time stamps given in context diff headers, assuming that the context diff headers use local time. This option is not recommended, because patches using local time cannot easily be used by people in other time zones, and because local time stamps are ambiguous when local clocks move backwards during daylight-saving time adjustments. Instead of using this option, generate patches with UTC and use the -Z or --set-utc option instead.
-u or --unified
Interpret the patch file as a unified context diff.

Validate Patch File Without Applying or Dry run

We may want to only validate or see the result of the patching. There is a option for this feature. We will use --dry-run option to only emulate patching process but not change any file really.

patch --dry-run < myapp.patch

Some recommedations

From the man page

There are several things you should bear in mind if you are going to be sending out patches.

Create your patch systematically. A good method is the command diff -Naur old new where old and new identify the old and new directories. The names old and new should not contain any slashes. The diff command's headers should have dates and times in Universal Time using traditional Unix format, so that patch recipients can use the -Z or --set-utc option. Here is an example command, using Bourne shell syntax:

LC_ALL=C TZ=UTC0 diff -Naur gcc-2.7 gcc-2.8

Tell your recipients how to apply the patch by telling them which directory to cd to, and which patch options to use. The option string -Np1 is recommended. Test your procedure by pretending to be a recipient and applying your patch to a copy of the original files.

You can save people a lot of grief by keeping a patchlevel.h file which is patched to increment the patch level as the first diff in the patch file you send out. If you put a Prereq: line in with the patch, it won't let them apply patches out of order without some warning.

You can create a file by sending out a diff that compares /dev/null or an empty file dated the Epoch (1970-01-01 00:00:00 UTC) to the file you want to create. This only works if the file you want to create doesn't exist already in the target directory. Conversely, you can remove a file by sending out a context diff that compares the file to be deleted with an empty file dated the Epoch. The file will be removed unless patch is conforming to POSIX and the -E or --remove-empty-files option is not given. An easy way to generate patches that create and remove files is to use GNU diff's -N or --new-file option.

If the recipient is supposed to use the -pN option, do not send output that looks like this:

                           diff -Naur v2.0.29/prog/README prog/README 
                           --- v2.0.29/prog/README     Mon Mar 10 
15:13:12 1997 
                           +++ prog/README     Mon Mar 17 14:58:22 1997  
because the two file names have different numbers of slashes, and different versions of patch interpret the file names differently. To avoid confusion, send output that looks like this instead:
 
                           diff -Naur v2.0.29/prog/README v2.0.30/prog/README 
                           --- v2.0.29/prog/README     Mon Mar 10 
15:13:12 1997 
                           +++ v2.0.30/prog/README     Mon Mar 17 14:58:22 1997 

Avoid sending patches that compare backup file names like README.orig, since this might confuse patch into patching a backup file instead of the real file. Instead, send patches that compare the same base file names in different directories, e.g. old/README and new/README.

Take care not to send out reversed patches, since it makes people wonder whether they already applied the patch.

Try not to have your patch modify derived files (e.g. the file configure where there is a line configure: configure.in in your makefile), since the recipient should be able to regenerate the derived files anyway. If you must send diffs of derived files, generate the diffs using UTC, have the recipients apply the patch with the -Z or --set-utc option, and have them remove any unpatched files that depend on patched files (e.g. with make clean).

While you may be able to get away with putting 582 diff listings into one file, it may be wiser to group related patches into separate files in case something goes haywire.


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Feb 17, 2020] 7 Patch Command Examples to Apply Diff Patch Files in Linux by Lakshmanan Ganapathy

Dec 2, 2014

... ... ...

A patch file is a text file which contains the differences between two versions of the same file (or same source-tree). Patch file is created by using diff command.

1. Create a Patch File using diff

To understand this, let us create a small C program named hello.c

#include <stdio.h> 

int main() {
printf("Hello World\n");
}

Now, copy the hello.c to hello_new.c

$ cp hello.c hello_new.c

Edit the hello_new.c as shown below to make some small changes:

#include <stdio.h>

int main(int argc, char *argv[]) {
printf("Hello World\n");
return 0;
}

Finally, create the patch file using diff command as shown below:

$ diff -u hello.c hello_new.c > hello.patch

The above command will create a patch file named "hello.patch".

--- hello.c	2014-10-07 18:17:49.000000000 +0530
+++ hello_new.c	2014-10-07 18:17:54.000000000 +0530
@@ -1,5 +1,6 @@
 #include <stdio.h>
 
-int main() {
+int main(int argc, char *argv[]) {
 	printf("Hello World\n");
+	return 0;
 }
2. Apply Patch File using Patch Command

The "patch" command takes a patch file as input and apply the differences to one or more original file(s), producing patched versions.

patch -p[num] < patchfile
patch [options] originalfile patchfile 

Use the patch command as shown below to apply the hello.patch to the original hello.c source code.

$ patch < hello.patch
patching file hello.c

The hello.patch file contains the name of the file to be patched. Once the file is patched, both hello.c and hello_new.c will have the content.

3. Create a Patch From a Source Tree

The above example was so simple that it works only with one file. We will see how to create and apply patch for a complete source tree by taking "openvpn" source code as example.

I've downloaded 2 version of openvpn, openvpn-2.3.2 and openvpn-2.3.4.

tar -xvzf openvpn-2.3.2.tar.gz

tar -xvzf openvpn-2.3.4.tar.gz

Now we will create the patch using the following command.

diff -Naur /usr/src/openvpn-2.3.2 /usr/src/openvpn-2.3.4 > openvpn.patch

The above command will operate recursively and find the differences, and place those differences in the patch file.

4. Apply Patch File to a Source Code Tree

The following patch commands can be used to apply the patch to source tree.

# patch -p3 < /root/openvpn.patch
patching file openvpn-2.3.2/aclocal.m4
patching file openvpn-2.3.2/build/Makefile.in
patching file openvpn-2.3.2/build/msvc/Makefile.in
...

Please note that we are executing the command from /usr/src/. The patch file contains all the filenames in absolute path format( from root ). So when we execute from /usr/src, without the "-p" option, it will not work properly.

-p3 tells the patch command to skip 3 leading slashes from the filenames present in the patch file. In our case, the filename in patch file is "/usr/src/openvpn-2.3.2/aclocal.m4", since you have given "-p3", 3 leading slashes, i.e. until /usr/src/ is ignored.

5. Take a Backup before Applying the Patch using -b

You can take a backup of the original file before applying the patch command using the -b option as shown below.

$ patch -b < hello.patch
patching file hello.c

Now you will have a file name "hello.c.orig", which is the backup of the original hello.c.

You can also use -V to decide the backup filename format as shown below. Now you will have a file name "hello.c.~1~".

$ patch -b -V numbered < hello.patch
patching file hello.c
6. Validate the Patch without Applying (Dry-run Patch File)

You can dry run the patch command to see if you are getting any errors, without patching the file using –dry-run option as shown below.

$ patch --dry-run < hello.patch
patching file hello.c

You can see that hello.c is not modified at all.

7. Reverse a Patch that is Already Applied (Undo a Patch)

You can use the -R option to reverse a patch which is applied already.

$ patch < hello.patch
patching file hello.c

$ ls -l hello.c
-rw-r--r-- 1 lakshmanan users  94 2014-10-07 20:05 hello.c

$ patch -R < hello.patch
patching file hello.c

$ ls -l hello.c
-rw-r--r-- 1 lakshmanan users  62 2014-10-07 20:04 hello.c

You can notice from the filesize, that the patch, which is applied already is reversed when we used the -R option.

Recommended Links

Google matched content

Softpanorama Recommended

Top articles

Sites

Patch (computing) - Wikipedia, the free encyclopedia

patchutils

An Introduction to Patch LG #32 - Linux Documentation Project

7 Patch Command Examples to Apply Diff Patch Files in Linux

HowTo Apply a Patch File To My Linux - UNIX Source Code - nixCraft

Introduction Using diff and patch – Linux Academy

Patch Command Tutorial With Examples For Linux – POFTUT



Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2020 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) in the author free time and without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: February 17, 2020