PATCH(1)

NAME
patch - apply a diff file to an original

SYNOPSIS
patch [options] [originalfile [patchfile]]

but usually just

patch -pnumber <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; see the -V or --version-control 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 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.

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 a diff listing to patch, and it should work. If the entire diff is indented by a consistent amount, this is taken into account.

With context diffs, and to a lesser extent with normal diffs, patch can detect when the line numbers mentioned in the patch are incorrect, and attempts 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 offset used 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 context given 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 the maximum 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 factor is 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.) 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 file plus a .rej suffix, or # if .rej would generate a file name that is too long (if even appending the single character # makes the file name too long, then # replaces the file name's last character). (The rejected hunk comes out in ordinary context diff form regardless of the input patch's form. If the input was a normal diff, many of the contexts are simply null.) The line numbers on the hunks 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 file rather 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 --verbose option is given, you are also told about hunks that succeeded. If the hunk is 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 was installed 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 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 to edit is. If the header is that of a context diff, patch takes the old and new file names in the header, and if there is an Index: line in the leading garbage, patch obtains the name in that line; any /dev/null names are ignored. These names are considered to be in the order (old, new, index), regardless of the order that they appear in the header. If some of the named files exist, patch uses the first name if the POSIXLY_CORRECT environment variable is set, and the best name otherwise. If no named files exist, some names are given, POSIXLY_CORRECT is not set, and the patch appears to create a file, patch uses the best name requiring the creation of the fewest directories. If no file name results from the above heuristics, you are asked for the name of the file to patch. 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, it then 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 version number) and checks the original file to see if that word can be found. If not, patch asks for confirmation before proceeding.

If an RCS file is handy, and the original file cannot be found or is read-only and matches the default version, and if version control (see the -V or --version-control option) is set to existing, patch attempts to get and lock the file. SCCS is treated in a similar way.

The upshot of all this is that you should be able to say, while in a news interface, something like the following:

    | patch -d /usr/src/local/blurfl

and patch a file in the blurfl directory directly from the article containing the patch.

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 other things, 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 contains interesting things such as file names and revision level, as mentioned previously.

OPTIONS

-b  or  --backup
    Make backup files. This option is equivalent to --version-control=simple; see the -V or --version-control option for details. In older versions of patch, this option had an argument specifying the simple backup suffix; this argument has been moved to the -z option.

-B pref  or  --prefix=pref
    Prefix simple backup file names with pref. For example, with -B /junk/ the simple backup file name for src/patch/util.c is /junk/src/patch/util.c.

--binary
    Read and write all files in binary mode, except for standard output and /dev/tty. This option has no effect on POSIX-compliant systems. On systems like DOS where this option makes a difference, the patch should be generated by diff -a --binary.

-c  or  --context
    Interpret the patch file as a ordinary context diff.

--verbose
    Output extra information about the work being done.

-d dir  or  --directory=dir
    Change to the directory dir immediately, before doing anything else.

-D sym  or  --ifdef=sym
    Use the #ifdef ... #endif construct to mark changes, with sym as the differentiating symbol.

--dry-run
    Print the results of applying the patches without actually changing any files.

-e  or  --ed
    Interpret the patch file as an ed script.

-E  or  --remove-empty-files
    Remove output files that are empty after the patches have been applied. Normally this option is unnecessary, since patch can examine the timestamps on the header to determine whether a file should exist after patching. However, if the input is not a context diff or if the POSIXLY_CORRECT environment variable is set, patch does not remove empty patched files unless this option is given. When patch removes a file, it also attempts to remove any empty ancestor directories.

-f  or  --force
    Assume that the user knows exactly what he or she is doing, and do not ask any questions. Skip patches whose headers do not say which file is to be patched; patch files even though they have the wrong version for the Prereq: line in the patch; and assume that patches are not reversed even if they look like they are. This option does not suppress commentary; use -s for that.

-F number  or  --fuzz=number
    Set the maximum fuzz factor. This option only applies to diffs that have context, and causes patch to ignore up to that many lines in looking for places to install a hunk. Note that a larger fuzz factor increases the odds of a faulty patch. The default fuzz factor is 2, and it may not be set to more than the number of lines of context in the context diff, ordinarily 3.

-g  or  --get
    If a file does not exist or is read-only and matches the default version, get it from RCS if it is under RCS control; similarly for SCCS. If the PATCH_GET environment variable is set, this is the default.

-G  or  --no-get
    Do not get files from RCS or SCCS. This is the default unless the PATCH_GET environment variable is set.

--help
    Print a summary of options and exit.

-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 file  or  --output=file
    Send output to file instead of patching files in place.

-pnumber  or  --strip=number
    Strip the smallest prefix containing number 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. With GNU patch, the two-argument -p N form of this option is equivalent to one-argument -pN form, but this is not true of traditional patch, so the one-argument form is recommended for portability.

-r file  or  --reject-file=file
    Put rejects into file instead of the default .rej file.

-R  or  --reverse
    Assume that this patch was created with the old and new files swapped. (Yes, I'm afraid that does happen occasionally, human nature being what it is.) patch attempts to swap each hunk around before applying it. Rejects come out in the swapped format. The -R option does not work with ed diff scripts because there is too little information to reconstruct the reverse operation.

    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 if the 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.)

-s  or  --silent  or  --quiet
    Work silently, unless an error occurs.

-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.

-u  or  --unified
    Interpret the patch file as a unified context diff.

-v  or  --version
    Print out patch's revision header and patch level, and exit.

-V method  or  --version-control=method
    Use method when creating backup file names. The type of backups made can also be given in the PATCH_VERSION_CONTROL (or, if that's not set, the VERSION_CONTROL) environment variable, which is overridden by this option.

    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):

    existing  or  nil
        Make numbered backups of files that already have them, otherwise simple backups.

    none
        Do not make backups. This is the default.

    numbered  or  t
        Make numbered backups. The numbered backup file name for F is F.~N~ where N is the version number.

    simple  or  never
        Make simple backups. That is, when patching a file F, rename or copy the original instead of removing it. The -B or --prefix, -y or --basename-prefix, and -z or --suffix options specify the simple backup file name. If none of these options are given, then a simple backup suffix is used; it is the value of the SIMPLE_BACKUP_SUFFIX environment variable if set, and is .orig otherwise.

    With numbered or simple backups, if the backup file name is too long, the backup suffix ~ is used instead; if even appending ~ would make the name too long, then ~ replaces the last character of the file name.

-x number  or  --debug=number
    Set internal debugging flags of interest only to patch patchers.

-y pref  or  --basename-prefix=pref
    Prefix the basename of the simple backup file name with pref. For example, with -y .del/ the backup file name for src/patch/util.c is src/patch/.del/util.c.

-z suff  or  --suffix=suff
    Use suff as the simple backup suffix. The backup extension may also be specified by the SIMPLE_BACKUP_SUFFIX environment variable, which is overridden by this option.

ENVIRONMENT

POSIXLY_CORRECT
    If set, patch conforms more strictly to the POSIX standard: it takes the first existing file when intuiting file names from diff headers, it does not remove files that are empty after patching, and it requires that all options precede the files in the command line.

SIMPLE_BACKUP_SUFFIX
    Extension to use for simple backup file names instead of .orig.

TMPDIR, TMP, TEMP
    Directory to put temporary files in; patch uses the first environment variable in this list that is set. If none are set, the default is system-dependent; it is normally /tmp on Unix hosts.

PATCH_VERSION_CONTROL or VERSION_CONTROL
    Selects version control style; see the -v or --version-control option.

PATCH_GET
    If set, patch gets missing or read-only files from RCS or SCCS by default; see the -g or -- get and the -G or -- no-get options.

FILES

$TMPDIR/p*
    temporary files

/dev/tty
    console; used to get answers to questions asked of the user

SEE ALSO
diff(1), ed(1)

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 -Naur old new where old and new identify the old and new directories. The names old and new should not contain any slashes. Here is an example:

    diff -Naur version-2.2 version-2.3

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.

Make sure you've specified the file names right, either in a context diff header, or with an Index: line.

You can create a file by sending out a diff that compares an empty file (such as /dev/null) 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 diff that compares the file to be deleted with an empty file. The file will be removed unless the POSIXLY_CORRECT environment variable is set 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 --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, ensure that the diffs for each derived file follow the diffs for the files that it depends on, so that the dependencies will be preserved as patch updates the files one by one. Here is a sample shell script that output patches in an order that should preserve dependencies:

#! /bin/sh

old=${1?}
new=${2?}

fs=
for f in `
  diff -Nqr $old $new |
  sed -e "s,.* $new/,," -e 's, differ$,,'`
do
  if [ -f $new/$f ]
  then fs="$fs $f"
  else diff -au $old/$f /dev/null
  fi
done

case $fs in
?*)
  for f in `cd $new; ls -rt $fs`
  do
    if [ -f $old/$f ]
    then diff -au $old/$f $new/$f
    else diff -au /dev/null $new/$f
    fi
  done
esac

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.

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 is attempting 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, and 2 if there is more 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 partially patched 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 they represent 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 or deletion. A context diff using fuzz factor 3 may have the same problem. Until a suitable interactive interface is added, 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 the patch is applied to exactly the same version of the file that the patch was generated from.

BUGS
patch could be smarter about partial matches, excessively deviant offsets and swapped code, but that would take an extra pass.

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 a feature.

COPYING
Copyright 1984, 1985, 1986, 1988 Larry Wall.
Copyright 1997 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 all copies.

Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived 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, except that 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, and made it conform better to POSIX. Other contributors include Wayne Davison, who added unidiff support, and David MacKenzie, who added configuration and backup support.