Skip to content

Linux command: Diff/Patch ​

diff will calculate the difference of two files or folders and output with specific format. patch parse that specific format and apply difference to files or folders.

Example for Files ​

Here we prepare two files: file1.old.cpp and file1.new.cpp

cpp
// file1.old.cpp
#include <iostream>

int main() {
    return 0;
}
cpp
// file1.new.cpp
#include <iostream>

int main() {
    std::cout << "hello world" << std::endl;
    return 0;
}

Then the command can be:

bash
diff -Naur file1.old.cpp file1.new.cpp > patch.diff

The patch.diff will be:

diff
--- file1.old.cpp    2021-11-03 14:32:34.000000000 +0800
+++ file1.new.cpp    2021-11-03 14:33:00.000000000 +0800
@@ -1,5 +1,6 @@
 #include <iostream>

int main() {
**+    std::cout << "hello world" << std::endl;
**    return 0;
 }
\ No newline at end of file

-Naur Parameters ​

  • N: Treat removed file as empty. 
    This parameter allow patch command to remove or create files.
  • a: Allow calculating difference of binary file.
  • r: Recursively visit the folder tree.
  • u: Specific format output of difference.

-u: Specific format ​

Without this parameter, we’ll get the format below, and the patch command cannot parse it.

bash
$ diff file1.old.cpp file1.new.cpp > patch.diff
$ cat patch.diff
3a4
>     std::cout << "hello world" << std::endl;
$ patch -p0 < patch.diff
patch: **** Only garbage was found in the patch input.

Example for Folder ​

old
├── main.cpp (file1.old.cpp)
└── legacy
      └── 1.txt
new
└── main.cpp (file1.new.cpp)

This example has a absent file: old/legacy/1.txt and diff treat new/legacy/1.txt as an empty file with timestamp = unix time 0.

diff
diff -Naur old/legacy/1.txt new/legacy/1.txt
--- old/legacy/1.txt    2021-11-03 14:47:46.000000000 +0800
+++ new/legacy/1.txt    **1970-01-01 08:00:00.000000000 +0800**
@@ -1 +0,0 @@
-123
\ No newline at end of file
diff -Naur old/main.cpp new/main.cpp
--- old/main.cpp    2021-11-08 11:55:32.000000000 +0800
+++ new/main.cpp    2021-11-08 11:55:35.000000000 +0800
@@ -1,5 +1,6 @@
 #include <iostream>

int main() {
+    std::cout << "hello world" << std::endl;
    return 0;
 }
\ No newline at end of file

Patch ​

Patch old version to new version:

bash
diff -Naur file1.old.cpp file1.new.cpp > patch.diff
patch -p0 < patch.diff

“Patch” new version to old version:

bash
patch -p0 < patch.diff -R

Reference ​

Changelog

Just observe 👀