首页·终端命令

diff

文本处理

用法

diff -u [old] [new]

显示两个文件之间改了什么;patch 和代码评审期待的是 -u 统一格式,而有差异时退出码是 1,会让开了 set -e 的脚本中断。

常用选项

选项含义
-uUnified output, the format patch and code review expect
-rCompare two directory trees
-qOnly say whether the files differ
-wIgnore all whitespace
-iIgnore case
-NTreat a missing file as empty, which patches need

示例

diff -u old.conf new.conf > fix.patch

Writes a patch file.

diff -rq dirA dirB

Lists which files differ between two trees.

diff <(sort a.txt) <(sort b.txt)

Compares two files ignoring line order (bash).

它们本来就是用管道串起来用的。串三条往往比让一条命令做完所有事更短。

怎么看

  • 方括号 [ ] 表示这部分可以不写。
  • 省略号 … 表示可以写多个。
  • 选项区分大小写——有些命令里 -r 和 -R 不是一回事。

常见问题

Q. diff 是做什么的?

显示两个文件之间改了什么;patch 和代码评审期待的是 -u 统一格式,而有差异时退出码是 1,会让开了 set -e 的脚本中断。

Q. 怎么写?

diff -u [old] [new] —— 方括号表示可以省略的部分。

Q. 值得记的选项有几个?

这里列了 6 个,完整列表在 man diff。这条命令属于文本处理。

相关命令

man 手册: man diff