From Surf Wiki (app.surf) — the open knowledge base
Diff
Shell command for comparing file content
Shell command for comparing file content
| Field | Value |
|---|---|
| name | diff |
| title | diff |
| screenshot | |
| author | Douglas McIlroy |
| (AT&T Bell Laboratories) | |
| developer | Various open-source and commercial developers |
| released | |
| latest release date | |
| programming language | C |
| operating system | Unix, Unix-like, V, Plan 9, Inferno |
| platform | Cross-platform |
| genre | Command |
| license | Plan 9: MIT License |
the command with Unix heritage
(AT&T Bell Laboratories)
**diff** is a shell command that compares the content of files and reports differences. The term diff is also used to identify the output of the command and is used as a verb for running the command. To diff files, one runs diff to create a diff.
Typically, the command is used to compare text files, but it does support comparing binary files. If one of the input files contains non-textual data, then the command defaults to brief-mode in which it reports only a summary indication of whether the files differ. With the option, it always reports line-based differences, but the output may be difficult to understand since binary data is generally not structured in lines like text is.
Although the command is primarily used ad hoc to analyze changes between two files, a special use is for creating a patch file for use with the patch command which was specifically designed to use a diff output report as a patch file.
POSIX standardized the and commands including their shared file format.
History
The original utility was developed in the early 1970s for the Unix operating system, at Bell Labs in Murray Hill, New Jersey. It was part of the 5th Edition of Unix released in 1974, and was written by Douglas McIlroy, and James Hunt. This research was published in a 1976 paper co-written with James W. Hunt, who developed an initial prototype of . The algorithm this paper described became known as the Hunt–Szymanski algorithm.
McIlroy's work was preceded and influenced by Steve Johnson's comparison program on GECOS and Mike Lesk's program. also originated on Unix and, like , produced line-by-line changes and even used angle-brackets ("" and "
In the context of Unix, the use of the line editor provided with the natural ability to create machine-usable "edit scripts". These edit scripts, when saved to a file, can, along with the original file, be reconstituted by into the modified file in its entirety. This greatly reduced the secondary storage necessary to maintain multiple versions of a file. McIlroy considered writing a post-processor for where a variety of output formats could be designed and implemented, but he found it more frugal and simpler to have be responsible for generating the syntax and reverse-order input accepted by the command.
In 1984, Larry Wall created the utility (releasing its source code on the mod.sources and net.sources newsgroups{{cite newsgroup | message-id = 1457@sdcrdcf.UUCP | access-date = May 11, 2015 | archive-date = February 19, 2022 | archive-url = https://web.archive.org/web/20220219233604/https://groups.google.com/g/net.sources/c/qtfVio1sSHs/m/G0cPT5HFDFcJ | url-status = live | message-id = 1508@sdcrdcf.UUCP | access-date = May 11, 2015 | archive-date = March 21, 2020 | archive-url = https://web.archive.org/web/20200321140052/https://groups.google.com/forum/ | url-status = live | message-id = 813@genrad.UUCP | access-date = May 11, 2015 | archive-date = February 19, 2022 | archive-url = https://web.archive.org/web/20220219233604/https://groups.google.com/g/mod.sources/c/xSQM63e39YY/m/apNNJSkJi0gJ | url-status = live
X/Open Portability Guide issue 2 of 1987 includes diff. Context mode was added in POSIX.1-2001 (issue 6). Unified mode was added in POSIX.1-2008 (issue 7).
In 's early years, common uses included comparing changes in the source of software code and markup for technical documents, verifying program debugging output, comparing filesystem listings and analyzing computer assembly code. The output targeted for was motivated to provide compression for a sequence of modifications made to a file. The Source Code Control System (SCCS) and its ability to archive revisions emerged in the late 1970s as a consequence of storing edit scripts from .
Algorithm
Unlike edit distance notions used for other purposes, is line-oriented rather than character-oriented, but it is like Levenshtein distance in that it tries to determine the smallest set of deletions and insertions to create one file from the other.
The operation of is based on solving the longest common subsequence problem. In this problem, given two sequences of items:
h q
e i k r x y
and we want to find a longest sequence of items that is present in both original sequences in the same order. That is, we want to find a new sequence which can be obtained from the first original sequence by deleting some items, and from the second original sequence by deleting other items. We also want this sequence to be as long as possible. In this case it is
a b c d f g j z
From a longest common subsequence it is only a small step to get -like output: if an item is absent in the subsequence but present in the first original sequence, it must have been deleted (as indicated by the '-' marks, below). If it is absent in the subsequence but present in the second original sequence, it must have been inserted (as indicated by the '+' marks).
e h i q k r x y
Use
The diff command accepts two arguments like: diff *original* *new*. Commonly, the arguments each identify normal files, but if the two arguments identify directories, then the command compares corresponding files in the directories. With the -r option, it recursively descends matching subdirectories to compare files with corresponding relative paths.
Default output format
The example below shows the original and new file content as well as the resulting diff output in the default format. The output is shown with coloring to improve readability. By default, diff outputs plain text, but GNU diff does use color highlighting when the option is used.
original:
This part of the
document has stayed the
same from version to
version. It shouldn't
be shown if it doesn't
change. Otherwise, that
would not be helping to
compress the size of the
changes.
This paragraph contains
text that is outdated.
It will be deleted in the
near future.
It is important to spell
check this dokument. On
the other hand, a
misspelled word isn't
the end of the world.
Nothing in the rest of
this paragraph needs to
be changed. Things can
be added after it.
new:
This is an important
notice! It should
therefore be located at
the beginning of this
document!
This part of the
document has stayed the
same from version to
version. It shouldn't
be shown if it doesn't
change. Otherwise, that
would not be helping to
compress the size of the
changes.
It is important to spell
check this document. On
the other hand, a
misspelled word isn't
the end of the world.
Nothing in the rest of
this paragraph needs to
be changed. Things can
be added after it.
This paragraph contains
important new additions
to this document.
output: 0a1,6 notice! It should therefore be located at the beginning of this document! 11,15d16 17c18
24a26,29 This paragraph contains important new additions to this document.}}}}
In this default format, stands for added, for deleted and for changed. The line number of the original file appears before the single-letter code and the line number of the new file appears after. The less-than and greater-than signs (at the beginning of lines that are added, deleted or changed) indicate which file the lines appear in. Addition lines are added to the original file to appear in the new file. Deletion lines are deleted from the original file to be missing in the new file.
By default, lines common to both files are not shown. Lines that have moved are shown as added at their new location and as deleted from their old location. However, some diff tools highlight moved lines.
variations
Edit script
An ed script can be generated by modern versions of diff with the -e option. The resulting edit script for this example is as follows:
24a
This paragraph contains important new additions to this document. . 17c check this document. On . 11,15d 0a This is an important notice! It should therefore be located at the beginning of this document!
.
In order to transform the content of the original file into the content of new file using , one appends two lines to this diff file, one line containing a w (write) command, and one containing a q (quit) command (e.g. by ). Here we gave the diff file the name mydiff and the transformation will then happen when we run {{code|lang=bash|ed -s original
Context format
The Berkeley distribution of Unix made a point of adding the context format () and the ability to recurse on filesystem directory structures (), adding those features in 2.8 BSD, released in July 1981. The context format of diff introduced at Berkeley helped with distributing patches for source code that may have been changed minimally.
In the context format, any changed lines are shown alongside unchanged lines before and after. The inclusion of any number of unchanged lines provides a context to the patch. The context consists of lines that have not changed between the two files and serve as a reference to locate the lines' place in a modified file and find the intended location for a change to be applied regardless of whether the line numbers still correspond. The context format introduces greater readability for humans and reliability when applying the patch, and an output which is accepted as input to the patch program. This intelligent behavior is not possible with the traditional diff output.
The number of unchanged lines shown above and below a change hunk can be defined by the user, even zero, but three lines is typically the default. If the context of unchanged lines in a hunk overlap with an adjacent hunk, then diff will avoid duplicating the unchanged lines and merge the hunks into a single hunk.
A "" represents a change between lines that correspond in the two files, whereas a "" represents the addition of a line, and a "" the removal of a line. A blank space represents an unchanged line. At the beginning of the patch is the file information, including the full path and a time stamp delimited by a tab character. At the beginning of each hunk are the line numbers that apply for the corresponding change in the files. A number range appearing between sets of three asterisks applies to the original file, while sets of three dashes apply to the new file. The hunk ranges specify the starting and ending line numbers in the respective file.
The command produces the following output:
*** /path/to/original timestamp
--- /path/to/new timestamp
***************
*** 1,3 ****
--- 1,9 ----
+ This is an important
+ notice! It should
+ therefore be located at
+ the beginning of this
+ document!
+
This part of the
document has stayed the
same from version to
***************
*** 8,20 ****
compress the size of the
changes.
- This paragraph contains
- text that is outdated.
- It will be deleted in the
- near future.
It is important to spell
! check this dokument. On
the other hand, a
misspelled word isn't
the end of the world.
--- 14,21 ----
compress the size of the
changes.
It is important to spell
! check this document. On
the other hand, a
misspelled word isn't
the end of the world.
***************
*** 22,24 ****
--- 23,29 ----
this paragraph needs to
be changed. Things can
be added after it.
+
+ This paragraph contains
+ important new additions
+ to this document.
Unified format
The unified format (or unidiff) inherits the technical improvements made by the context format, but produces a smaller diff with old and new text presented immediately adjacent. Unified format is usually invoked using the "-u" command-line option. This output is often used as input to the patch program. Many projects specifically request that "diffs" be submitted in the unified format, making unified diff format the most common format for exchange between software developers.
Unified context diffs were originally developed by Wayne Davison in August 1990 (in unidiff which appeared in Volume 14 of comp.sources.misc). Richard Stallman added unified diff support to the GNU Project's diff one month later, and the feature debuted in GNU diff 1.15, released in January 1991. GNU diff has since generalized the context format to allow arbitrary formatting of diffs.
The format starts with the same two-line header as the context format, except that the original file is preceded by "---" and the new file is preceded by "+++". Following this are one or more change hunks that contain the line differences in the file. The unchanged, contextual lines are preceded by a space character, addition lines are preceded by a plus sign, and deletion lines are preceded by a minus sign.
A hunk begins with range information and is immediately followed with the line additions, line deletions, and any number of the contextual lines. The range information is surrounded by double at signs, and combines onto a single line what appears on two lines in the context format (above). The format of the range information line is as follows:
@@ -l,s +l,s @@ optional section heading ruins the italics --
The hunk range information contains two hunk ranges. The range for the hunk of the original file is preceded by a minus symbol, and the range for the new file is preceded by a plus symbol. Each hunk range is of the format l,s where l is the starting line number and s is the number of lines the change hunk applies to for each respective file. In many versions of GNU diff, each range can omit the comma and trailing value s, in which case s defaults to 1. Note that the only really interesting value is the l line number of the first range; all the other values can be computed from the diff.
The hunk range for the original should be the sum of all contextual and deletion (including changed) hunk lines. The hunk range for the new file should be a sum of all contextual and addition (including changed) hunk lines. If hunk size information does not correspond with the number of lines in the hunk, then the diff could be considered invalid and be rejected.
Optionally, the hunk range can be followed by the heading of the section or function that the hunk is part of. This is mainly useful to make the diff easier to read. When creating a diff with GNU diff, the heading is identified by regular expression matching.
If a line is modified, it is represented as a deletion and addition. Since the hunks of the original and new file appear in the same hunk, such changes would appear adjacent to one another. An occurrence of this in the example below is:
-check this dokument. On +check this document. On
The command diff -u original new produces the following output:
--- /path/to/original timestamp
+++ /path/to/new timestamp
@@ -1,3 +1,9 @@
+This is an important
+notice! It should
+therefore be located at
+the beginning of this
+document!
+
This part of the
document has stayed the
same from version to
@@ -8,13 +14,8 @@
compress the size of the
changes.
-This paragraph contains
-text that is outdated.
-It will be deleted in the
-near future.
-
It is important to spell
-check this dokument. On
+check this document. On
the other hand, a
misspelled word isn't
the end of the world.
@@ -22,3 +23,7 @@
this paragraph needs to
be changed. Things can
be added after it.
+
+This paragraph contains
+important new additions
+to this document.
To successfully separate the file names from the timestamps, the delimiter between them is a tab character. This is invisible on screen and can be lost when diffs are copy/pasted from console/terminal screens.
Extensions
There are some modifications and extensions to the diff formats that are used and understood by certain programs and in certain contexts. For example, some revision control systems—such as Subversion—specify a version number, "working copy", or any other comment instead of or in addition to a timestamp in the diff's header section.
Some tools allow diffs for several different files to be merged into one, using a header for each modified file that may look something like this:
Index: path/to/file.cpp
The special case of files that do not end in a newline is not handled. Neither nor the POSIX standard define a way to handle this type of files. (Indeed, such files are not "text" files by strict POSIX definitions.) GNU diff and git produce "\ No newline at end of file" (or a translated version) as a diagnostic, but this behavior is not portable. GNU patch does not seem to handle this case, while git-apply does.
The patch program does not necessarily recognize implementation-specific diff output. GNU patch is, however, known to recognize git patches and act a little differently.
References
References
- Eric S. Raymond (ed.), [http://catb.org/jargon/html/D/diff.html "diff"] {{Webarchive. link. (2014-01-31 , ''The Jargon File'', version 4.4.7)
- MacKenzie ''et al.'' "Binary Files and Forcing Text Comparison" in ''Comparing and Merging Files with GNU Diff and Patch''. Downloaded 28 April 2007. [https://www.gnu.org/software/diffutils/manual/html_node/Binary.html] {{Webarchive. link. (2017-12-19)
- (26 September 2008). "Standard for Information Technology—Portable Operating System Interface (POSIX) Base Specifications, Issue 7".
- (August 2025)
- (June 1976). "An Algorithm for Differential File Comparison". Computing Science Technical Report, Bell Laboratories.
- {{man. cu. diff. SUS
- (1997). "Comparing and Merging Files with GNU Diff and Patch". Network Theory.
- "Detailed Description of Unified Format".
- van Rossum, Guido. "Unified Diff Format".
- [https://www.gnu.org/software/diffutils/manual/html_node/Sections.html 2.2.3 Showing Which Sections Differences Are in], GNU diffutils manual
- [http://www.artima.com/weblogs/viewpost.jsp?thread=164293 Unified Diff Format] by [[Guido van Rossum]], June 14, 2006
- http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_403 {{Webarchive. link. (2013-04-29 Section 3.206)
- "Incomplete Lines (Comparing and Merging Files)".
- (8 May 2023). "git: apply.c". Git.
- "patch.c\src - patch.git - GNU patch".
- E. Myers. (1986). "An O(ND) Difference Algorithm and Its Variations". Algorithmica.
- (1985). "A File Comparison Program". Software: Practice and Experience.
- Esko Ukkonen. (1985). "Algorithms for Approximate String Matching". Information and Control.
- [https://www.gnu.org/software/diffutils/ GNU Diff utilities] {{Webarchive. link. (2015-03-16 . Made available by the [[Free Software Foundation]]. Free Documentation. Free source code.)
- "merge (GNU RCS 5.10.0)".
- Moolenaar, Bram. "Vim documentation: diff".
- Brabandt, Christian. (1 December 2018). "The power of diff".
- "gnu.org".
- "colordiff".
- (6 May 2023). "diff-so-fancy". So Fancy.
- (8 May 2023). "dandavison/delta".
- (12 June 2020). "twaugh/patchutils".
- (June 1990). "Identifying the semantic and textual differences between two versions of a program". ACM SIGPLAN Notices.
- (July 1991). "Identifying syntactic differences between two programs". Software: Practice and Experience.
- Grass. Cdiff: A syntax directed Diff for C++ programs. Proceedings USENIX C++ Conf., pp. 181-193, 1992
- Compare++, http://www.coodesoft.com/ {{Webarchive. link. (2011-11-29)
- SmartDifferencer, http://www.semanticdesigns.com/Products/SmartDifferencer {{Webarchive. link. (2009-10-14)
- (26 May 2020). "xaizek/zograscope".
- ''DaisyDiff'', https://code.google.com/p/daisydiff/ {{Webarchive. link. (2015-03-19)
- ''xmldiffpatch'', http://msdn.microsoft.com/en-us/library/aa302294.aspx {{Webarchive. link. (2009-10-27)
- ''xmldiffmerge'', http://www.alphaworks.ibm.com/tech/xmldiffmerge {{Webarchive. link. (2009-09-24)
- Cheney, Austin. ''Pretty Diff - Documentation''. http://prettydiff.com/documentation.php {{Webarchive. link. (2012-07-31)
- (1988-02-02). "SPIFF 1".
- Nachbar, Daniel W. (1988-02-02). "Man page".
- dontcallmedotcom. "spiff".
- Davide. (2009-09-28). "stackoverflow".
- Nachbar, Daniel W. (1999-12-01). "HP-UX Porting and Archiving".
- "LibXDiff".
- (January 2020). "How different are different diff algorithms in Git?: Use --histogram for code changes".
- "algorithm - What's the difference between 'git diff --patience' and 'git diff --histogram'?".
This article was imported from Wikipedia and is available under the Creative Commons Attribution-ShareAlike 4.0 License. Content has been adapted to SurfDoc format. Original contributors can be found on the article history page.
Ask Mako anything about Diff — get instant answers, deeper analysis, and related topics.
Research with MakoFree with your Surf account
Create a free account to save articles, ask Mako questions, and organize your research.
Sign up freeThis content may have been generated or modified by AI. CloudSurf Software LLC is not responsible for the accuracy, completeness, or reliability of AI-generated content. Always verify important information from primary sources.
Report