I have a file x1 in one directory (d1) and I'm not sure if the same file is already copied (x2) in another directory (d2) (but automatically renamed by application).

Can I check if hash of file x1 from directory d1 is equal to hash of some file x2 existing in directory d2?


This is a good approach, but the search will be a lot faster if you only calculate hashes of files that have the right size. Using GNU/BusyBox utilities:

wanted_size=$(stat -c %s d1/x1)
wanted_hash=$(sha256sum <d1/x1)
find d2 -type f -size "${wanted_size}c" -execdir sh -c 'test "$(sha256sum <"$0")" = "$1"' {} "$wanted_hash" \; -print
| improve this answer | |

To find a file with a known MD5 digest in a directory (using bash or ksh93):

x1digest="$( md5sum d1/x1 | cut -d ' ' -f 1 )"

for x2 in d2/*; do
    if [[ ! -f "$fpath" ]]; then

    x2digest="$( md5sum "$fpath" | cut -d ' ' -f 1 )"

    if [[ "$x2digest" == "$x1digest" ]]; then
      printf '"%s" has the same hash as d1/x1\n' "$fpath"

On BSD systems, md5sum filename | cut -d ' ' -f 1 can be replaced by md5 -q filename.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.