How To Apply Patch Linux
I would like to make a SVN type patch file for httpd.conf
so I can easily apply it to other hosts.
If I do
I get:
Question
How to Apply a Patch. The command or utility in Linux that is used to apply the patch is called patch. The patch program takes a patch file and applies the differences into one or more of the original file producing a final patched version of the file. Patch files usually have an extension of.patch although it is not. How to Generate and Apply Patches using diff and patch on Linux By Eric Ma In Linux, Programming Updated on Sep 19, 2017 diff and patch are tools to create patches and apply patches to source code, which is widely used in the open-source world, such as Linux kernel and application. You apply a patch with the patch program. The patch program reads a diff (or patch) file and makes the changes to the source tree described in it. Patches for the Linux kernel are generated relative to the parent directory holding the kernel source dir.
What am I doing wrong?
Sandra SchlichtingSandra Schlichting3 Answers
By default, patch
ignores the directory portion of the target filename; it's just looking for 'httpd.conf' in your current working directory. If you want it to use the full path, you have to explicitly ask it to do so with the -p
option:
patch -p 0 < httpd.patch
The number after -p
is how many levels to remove from the filename path; -p N
strips off everything up to and including slash number N. The first slash is number 1, so -p 0
means 'don't strip anything'.
In general, you might be better off not relying on having the full path in the patch file, though; the patch will be more generally useful if it works even for files in a different directory layout. You can always cd into the directory containing the file before running patch (and use a full path to find the patch file itself, if needed, instead).
Mark ReedMark ReedUse svn patch
.
Case 1: using /usr/bin/patch
:
Applies your changes well if there are no added/deleted files through svn add
or svn delete
Case 2: using svn patch
:
Tracks added and deleted files too.
Note that neither tracks svn move
s and rename
s
If you're using TortoiseSVN there is a easy to use interface to create and apply a patch.
To create:
Right click on folder -> TortoiseSVN -> Create patch
You will be prompted to select an output file
To apply:
Right click on folder -> TortoiseSVN -> Apply patch
You will be prompted with an interface to select the file(s) to apply the patches to, and merge if necassary.
James WierzbaJames WierzbaNot the answer you're looking for? Browse other questions tagged linuxdiffpatch or ask your own question.
Name
patch - apply a diff file to an original
Synopsis
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 ormore original files, producing patched versions. Normally the patched versions are put in place of the originals. 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 bespecified 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 thepatch program itself, while ed diffs are simply fed to the ed(1) editor via a pipe.
patch tries to skip any leading garbage, apply the diff, and then skip any trailing garbage. Thus you could feed an article or message containing adiff listing to patch, and it should work. If the entire diff is indented by a consistent amount, or if a context diff contains lines ending inCRLF or is encapsulated one or more times by prepending '- ' to lines starting with '-' as specified by Internet RFC 934, this istaken into account. After removing indenting or encapsulation, lines beginning with # are ignored, as they are considered to be comments.
With context diffs, and to a lesser extent with normal diffs, patch can detect when the line numbers mentioned in the patch are incorrect, andattempts to find the correct place to apply each hunk of the patch. As a first guess, it takes the line number mentioned for the hunk, plus or minus any offsetused in applying the previous hunk. If that is not the correct place, patch scans both forwards and backwards for a set of lines matching the contextgiven in the hunk. First patch looks for a place where all lines of the context match. If no such place is found, and it's a context diff, and themaximum fuzz factor is set to 1 or more, then another scan takes place ignoring the first and last line of context. If that fails, and the maximum fuzz factoris set to 2 or more, the first two and last two lines of context are ignored, and another scan is made. (The default maximum fuzz factor is 2.)
Hunks with less prefix context than suffix context (after applying fuzz) must apply at the start of the file if their first line number is 1. Hunks withmore prefix context than suffix context (after applying fuzz) must apply at the end of the file.
If patch cannot find a place to install that hunk of the patch, it puts the hunk out to a reject file, which normally is the name of the output fileplus a .rej suffix, or # if .rej would generate a file name that is too long (if even appending the single character # makes thefile name too long, then # replaces the file name's last character).
The rejected hunk comes out in unified or context diff format. If the input was a normal diff, many of the contexts are simply null. The line numbers on thehunks in the reject file may be different than in the patch file: they reflect the approximate location patch thinks the failed hunks belong in the new filerather than the old one.
As each hunk is completed, you are told if the hunk failed, and if so which line (in the new file) patch thought the hunk should go on. If the hunkis installed at a different line from the line number specified in the diff, you are told the offset. A single large offset may indicate that a hunk wasinstalled in the wrong place. You are also told if a fuzz factor was used to make the match, in which case you should also be slightly suspicious. If the--verbose option is given, you are also told about hunks that match exactly.
If no original file origfile is specified on the command line, patch tries to figure out from the leading garbage what the name of the file toedit is, using the following rules.
First, patch takes an ordered list of candidate file names as follows: Srs labs downloads.
•If the header is that of a context diff, patch takes the old and new file names in the header. A name is ignored if it does not have enough slashesto satisfy the -pnum or --strip=num option. The name /dev/null is also ignored.
•
If there is an Index: line in the leading garbage and if either the old and new names are both absent or if patch is conforming toPOSIX , patch takes the name in the Index: line.
•
For the purpose of the following rules, the candidate file names are considered to be in the order (old, new, index), regardless of the order that theyappear in the header.
If some of the named files exist, patch selects the first name if conforming to POSIX , and the best name otherwise.
•
If patch is not ignoring RCS , ClearCase, Perforce, and SCCS (see the -gnum or --get=numoption), and no named files exist but an RCS , ClearCase, Perforce, or SCCS master is found, patch selects the first namedfile with an RCS , ClearCase, Perforce, or SCCS master.
•
If no named files exist, no RCS , ClearCase, Perforce, or SCCS master was found, some names are given, patch is notconforming to POSIX , and the patch appears to create a file, patch selects the best name requiring the creation of the fewestdirectories.
•
If no file name results from the above heuristics, you are asked for the name of the file to patch, and patch selects that name.
To determine the best of a nonempty list of file names, patch first takes all the names with the fewest path name components; of those, itthen takes all the names with the shortest basename; of those, it then takes all the shortest names; finally, it takes the first remaining name.Additionally, if the leading garbage contains a Prereq: line, patch takes the first word from the prerequisites line (normally a versionnumber) and checks the original file to see if that word can be found. If not, patch asks for confirmation before proceeding.
The upshot of all this is that you should be able to say, while in a news interface, something like the following:
If the patch file contains more than one patch, patch tries to apply each of them as if they came from separate patch files. This means, among otherthings, that it is assumed that the name of the file to patch must be determined for each diff listing, and that the garbage before each diff listing containsinteresting things such as file names and revision level, as mentioned previously.
Options
-b or --backup
/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 directoryspecified by the -d option.
Take the first existing file from the list (old, new, index) when intuiting file names from diff headers.
•
Do not remove files that are empty after patching.
•
Do not ask whether to get files from RCS , ClearCase, Perforce, or SCCS .
•
Require that all options precede the files in the command line.
•
Do not backup files when there is a mismatch.
Quote names for the shell if they contain shell metacharacters or would cause ambiguous output.
Quote names as for a C language string.
escape
Quote as with c except omit the surrounding double-quote characters.
If the first hunk of a patch fails, patch reverses the hunk to see if it can be applied that way. If it can, you are asked if you want to have the-R option set. If it can't, the patch continues to be applied normally. (Note: this method cannot detect a reversed patch if it is a normal diff and ifthe first command is an append (i.e. it should have been a delete) since appends always succeed, due to the fact that a null context matches anywhere. Luckily,most patches add or change lines rather than delete them, so most reversed normal diffs begin with a delete, which fails, triggering the heuristic.)
The value of method is like the GNU Emacs 'version-control' variable; patch also recognizes synonyms that are more descriptive.The valid values for method are (unique abbreviations are accepted):
The -Z or --set-utc and -T or --set-time options normally refrain from setting a file's time if the file's original time doesnot match the time given in the patch header, or if its contents do not match the patch exactly. However, if the -f or --force option is given,the file time is set regardless.
Due to the limitations of diff output format, these options cannot update the times of files whose contents have not changed. Also, if you use theseoptions, you should remove (e.g. with make clean) all files that depend on the patched files, so that later invocations of make do not getconfused by the patched files' times.
Environment
PATCH_GET
- temporary files
- /dev/tty
- controlling terminal; used to get answers to questions asked of the user
See Also
diff(1), ed(1), merge(1).
Marshall T. Rose and Einar A. Stefferud, Proposed Standard for Message Encapsulation, Internet RFC 934 <URL:ftp://ftp.isi.edu/in-notes/rfc934.txt>(1985-01).
Notes For Patch Senders
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 -Naurold new where old and new identify the old and newdirectories. The names old and new should not contain any slashes. The diff command's headers should have dates and times in UniversalTime using traditional Unix format, so that patch recipients can use the -Z or --set-utc option. Here is an example command, using Bourne shellsyntax:
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 fileyou 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 thefile 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 bysending 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 conformingto POSIX and the -E or --remove-empty-files option is not given. An easy way to generate patches that create and remove files isto use GNUdiff'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 avoidconfusion, 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 ofthe 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 casesomething goes haywire.
Diagnostics
Diagnostics generally indicate that patch couldn't parse your patch file.
If the --verbose option is given, the message Hmm. indicates that there is unprocessed text in the patch file and that patch isattempting to intuit whether there is a patch in that text and, if so, what kind of patch it is.
patch's exit status is 0 if all hunks are applied successfully, 1 if some hunks cannot be applied or there were merge conflicts, and 2 if there ismore serious trouble. When applying a set of patches in a loop it behooves you to check this exit status so you don't apply a later patch to a partiallypatched file.
Caveats
Context diffs cannot reliably represent the creation or deletion of empty files, empty directories, or special files such as symbolic links. Nor can theyrepresent changes to file metadata like ownership, permissions, or whether one file is a hard link to another. If changes like these are also required,separate instructions (e.g. a shell script) to accomplish them should accompany the patch.
patch cannot tell if the line numbers are off in an ed script, and can detect bad line numbers in a normal diff only when it finds a change ordeletion. A context diff using fuzz factor 3 may have the same problem. You should probably do a context diff in these cases to see if the changes made sense.Of course, compiling without errors is a pretty good indication that the patch worked, but not always.
patch usually produces the correct results, even when it has to do a lot of guessing. However, the results are guaranteed to be correct only when thepatch is applied to exactly the same version of the file that the patch was generated from.
Compatibility Issues
The POSIX standard specifies behavior that differs from patch's traditional behavior. You should be aware of these differences if youmust interoperate with patch versions 2.1 and earlier, which do not conform to POSIX .
•In traditional patch, the -p option's operand was optional, and a bare -p was equivalent to -p0. The -p option nowrequires an operand, and -p 0 is now equivalent to -p0. For maximum compatibility, use options like -p0 and -p1.
In traditional patch, backups were enabled by default. This behavior is now enabled with the -b or --backup option.
Conversely, in POSIXpatch, backups are never made, even when there is a mismatch. In GNUpatch, this behavioris enabled with the --no-backup-if-mismatch option, or by conforming to POSIX with the --posix option or by setting thePOSIXLY_CORRECT environment variable.The -bsuffix option of traditional patch is equivalent to the -b -zsuffix options of GNUpatch.
•Traditional patch used a complicated (and incompletely documented) method to intuit the name of the file to be patched from the patch header. Thismethod did not conform to POSIX , and had a few gotchas. Now patch uses a different, equally complicated (but better documented) methodthat is optionally POSIX -conforming; we hope it has fewer gotchas. The two methods are compatible if the file names in the context diff headerand the Index: line are all identical after prefix-stripping. Your patch is normally compatible if each header's file names all contain the same numberof slashes.
•https://anhatosi1985.mystrikingly.com/blog/add-a-blog-post-title.
How To Apply Security Patch In Linux
When traditional patch asked the user a question, it sent the question to standard error and looked for an answer from the first file in thefollowing list that was a terminal: standard error, standard output, /dev/tty, and standard input. Now patch sends questions to standard outputand gets answers from /dev/tty. Defaults for some answers have been changed so that patch never goes into an infinite loop when using defaultanswers.
•
Traditional patch exited with a status value that counted the number of bad hunks, or with status 1 if there was real trouble. Now patch exitswith status 1 if some hunks failed, or with 2 if there was real trouble.
•
Limit yourself to the following options when sending instructions meant to be executed by anyone running GNUpatch, traditionalpatch, or a patch that conforms to POSIX . Spaces are significant in the following list, and operands are required.
-ddir
-Ddefine
-e
-l
-n
-N
-ooutfile
-pnum
-R
-rrejectfile
Bugs
Please report bugs via email to <bug-patch@gnu.org>.
If code has been duplicated (for instance with #ifdef OLDCODE . #else . #endif), patch is incapable of patching both versions, and,if it works at all, will likely patch the wrong one, and tell you that it succeeded to boot.
If you apply a patch you've already applied, patch thinks it is a reversed patch, and offers to un-apply the patch. This could be construed as afeature.
Computing how to merge a hunk is significantly harder than using the standard fuzzy algorithm. Bigger hunks, more context, a bigger offset from the originallocation, and a worse match all slow the algorithm down.
How To Use Linux Patch Command
Copying
Copyright © 1984, 1985, 1986, 1988 Larry Wall.
Copyright © 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2009 Free Software Foundation, Inc.
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on allcopies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resultingderived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, exceptthat this permission notice may be included in translations approved by the copyright holders instead of in the original English.
Authors
Larry Wall wrote the original version of patch. Paul Eggert removed patch's arbitrary limits; added support for binary files, setting filetimes, and deleting files; and made it conform better to POSIX . Other contributors include Wayne Davison, who added unidiff support, and DavidMacKenzie, who added configuration and backup support. Andreas Grünbacher added support for merging.