文件比较

if [[ $file1 -ef $file2 ]]; then
  echo "$file1 and $file2 are the same file"
fi

相同文件表示修改其中一个文件会影响另一个文件。两个文件即使具有不同的名称也可以是相同的,例如,如果它们是硬链接,或者它们是具有相同目标的符号链接,或者如果一个是指向另一个的符号链接。

如果两个文件具有相同的内容,但它们是不同的文件(因此修改一个文件不会影响另一个),则 -ef 会将它​​们报告为不同的文件。如果要逐个字节地比较两个文件,请使用 cmp 实用程序。

if cmp -s -- "$file1" "$file2"; then
  echo "$file1 and $file2 have identical contents"
else
  echo "$file1 and $file2 differ"
fi

要生成文本文件之间差异的人类可读列表,请使用 diff 实用程序。

if diff -u "$file1" "$file2"; then
  echo "$file1 and $file2 have identical contents"
else
  : # the differences between the files have been listed
fi