diff 在最簡單的情況下比較兩個檔案的差異。若把「文件」參數換成 -,要比較的內容就來自標準輸入。它以逐行方式比對文字檔案的異同;若指定的是目錄,則只比較兩個目錄中檔名相同的檔案,不會深入子目錄。
diff [選項參數] [文件1或目錄1] [文件2或目錄2]
指定檔案時只有文字檔才有效;指定目錄時,diff 會列出不同的二進位檔、共通子目錄,以及只存在於單一目錄中的檔案。
-y / --side-by-side:並列顯示差異。-W / --width:搭配 -y 時指定欄寬。-c:顯示全部內容並標出不同處。-u / -U / --unified:以合併方式顯示差異。-r / --recursive:遞迴比較子目錄。-n / --rcs:以 RCS 格式輸出比較結果。[root@localhost Document]# cat >t1.txt <<EOF this is a text! Name is t1.txt! The extra content! I am MenAngel! EOF [root@localhost Document]# diff ../Document/t1.txt ../Document/t2.txt 3,5c3 < Name is t1.txt! < The extra content! < I am MenAngel! --- > Name is t2.txt!
兩個參數可以是相對路徑也可以是絕對路徑。輸出中的 3,5c3 表示第一個檔案的第 3 到 5 行,對應第二個檔案的第 3 行,c 代表 change。
[root@localhost Document]# diff -y t1.txt t2.txt this is a text! this is a text! Name is t1.txt! | Name is t2.txt! The extra content! < I am MenAngel! <
[root@localhost Document]# diff -y -W 40 t1.txt t2.txt this is a text! this is a text! Name is t1.txt! | Name is t2.txt! The extra conten < I am MenAngel! <
[root@localhost Document]# diff -y -W 40 t2.txt t1.txt
this is a text! this is a text!
Name is t2.txt! | Name is t1.txt!
> The extra conten
> I am MenAngel!
說明:| 表示兩邊內容不同;< 表示後面的檔案比前面少一行;> 表示後面的檔案比前面多一行。
[root@localhost Document]# diff -c t1.txt t2.txt *** t1.txt 2016-05-27 23:31:25.949100752 -0700 --- t2.txt 2016-05-27 23:31:54.287100555 -0700 *************** *** 1,5 **** this is a text! ! Name is t1.txt! ! The extra content! ! I am MenAngel! --- 1,3 ---- this is a text! ! Name is t2.txt!
開頭兩行是檔案說明,! 表示兩者有差別的行;+ 與 - 則出現在 -u 參數的輸出中,分別代表後者多一行與少一行。
[root@localhost Document]# diff -u t1.txt t2.txt --- t1.txt 2016-05-27 23:31:25.949100752 -0700 +++ t2.txt 2016-05-27 23:31:54.287100555 -0700 @@ -1,5 +1,3 @@ this is a text! -Name is t1.txt! -The extra content! -I am MenAngel! +Name is t2.txt!
--- 是:first 檔案,+++ 是第二個檔案,@@ -1,5 +1,3 @@ 標示範圍。每個減號對應一個加號,沒有對應就代表另一邊沒有這行。
[root@localhost Document]# diff dir1 dir2 只在 dir2 存在:text3 diff dir1/text1 dir2/text1 1c1 < dir: dir1 --- > dir: dir2 4c4,5 < Total 4! --- > > Total 5! 只在 dir1 存在:text2
遇到同名檔案會自動比對,只存在於單邊的檔案則直接列出。
[root@localhost Document]# diff dir1 dir2 >dir.log [root@localhost Document]# cat dir.log
[root@localhost Document]# diff t1.txt t2.txt >t12.log [root@localhost Document]# patch t1.txt t12.log patching file t1.txt [root@localhost Document]# cat t1.txt this is a text! Name is t2.txt!
diff 是 Linux 上非常重要的工具,特別適合用來比較兩個版本不同的檔案以找出改動處,最新版本甚至支援二進位檔。它的輸出被稱為「補丁」(patch),因為系統中還有 patch 程式能依據 diff 的輸出把 a.c 更新成 b.c 的內容。正因如此,diff 是 svn、cvs、git 等版本控制工具不可或缺的基礎。