大网数据广告活动
服务器运维问答

Efficient way of determining whether 2 directories have ANY difference?

· 52CE 我爱测

I'd like to recursively compare two directory trees that are expected to be identical, but I don't want a full comparison which would take forever. I'd like to do an efficient comparison so that as soon as 1 difference is detecte…

问题原文

原帖链接 · jerkstorecalled · CC BY-SA 4.0

I'd like to recursively compare two directory trees that are expected to be identical, but I don't want a full comparison which would take forever. I'd like to do an efficient comparison so that as soon as 1 difference is detected, the command stops and returns, and tell me which file was different.

What I consider to be a difference:

  • two files have different content (different timestamps doesn't matter)
  • a file was found in one directory but not the other (at the exact same path, of course)

Notes:

  • I don't need to know the actual differences within the file, just the filepath is enough
  • I tried diff 3.7 on Ubuntu 20.04, it doesn't have a "stop on difference" option that I could see
  • The files are a mix of text and binary

已采纳解答

原帖链接 · Lacek · CC BY-SA 4.0

I don't know about a program which does this, but it is easy enough to write a small script calling diff and stopping upon the first difference. Like this:

#!/bin/bash

dir1="$1"
dir2="$2"

if [[ "*$dir1*$dir2*" == *"**"* ]]; then
    echo "Use: $0 dir1 dir2"
    exit 6
fi

while read line; do
    echo "The directory contents are different."
    exit 1
done < <(diff -qr "$dir1" "$dir2")
echo "The directory contents are the same."

This will pipe the output of diff into a read, which, upon receiving anything, exits the shell, killing the diff child process.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2021-03-04)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。