Diff
當文件不存在時,如何使 diff 列印完整的文件差異?
我正在嘗試將根文件系統上的文件與備份進行比較,我希望比較工作有點像添加
git
或刪除svn
diff
文件時- 也就是說,顯示完整文件 diff。不幸的是,只是列印一條消息,這不是很有用。我找不到這個選項。diff``No such file or directory
我能找到的最簡單的解決方法是解析
diff
輸出和diff -u path <(printf '')
/或diff -u <(printf '') path
取決於存在的路徑。這有點麻煩 - 可能是 10 行程式碼,這可能是一個簡單的diff
選項。另一種解決方法是
diff -u <([ -e "$path1" ] && cat "$path1") <([ -e "$path2" ] && cat "$path2")
,但這會失去差異中的文件名。
根據克雷格桑德斯的回答和之前的解決方法,我最終得到了這個:
diff -u \ "$([ -e "$path1" ] && echo "$path1" || echo /dev/null)" \ "$([ -e "$path2" ] && echo "$path2" || echo /dev/null)"
編輯:原來有一個選項:
-N, --new-file treat absent files as empty
換一種說法:
diff -Nu "$path1" "$path2"
至少使用某些版本的 GNU diffutils’
diff
,您可以使用該-N
標誌直接執行此操作(儘管文件似乎說僅適用於目錄差異)。$ ls foo $ cat foo foo $ diff -u foo bar diff: bar: No such file or directory $ diff -uN bar foo --- bar 1970-01-01 01:00:00.000000000 +0100 +++ foo 2012-09-04 12:45:34.000000000 +0200 @@ -0,0 +1 @@ +foo $ diff -uN foo bar --- foo 2012-09-04 12:45:34.000000000 +0200 +++ bar 1970-01-01 01:00:00.000000000 +0100 @@ -1 +0,0 @@ -foo $ diff -v diff (GNU diffutils) 2.8.1 Copyright (C) 2002 Free Software Foundation, Inc.