1
file=$3
#Using $3 as I am using 1 & 2 in the rest of the script[that works]
file_hash=md5sum "$file" | cut -d ' ' -f l
#generates hashes for file

for a in /path/to/source/* #loop for all files in directory
do
    if [ "$file_hash" == $(md5sum "$a" | cut -d ' ' -f l) ]:
    #if the file hash is equal to the hash generated then file is copied to path/to/source
    then cp "file" /path/to/source/*
    else cp "$file" "file.JPG" mv "file.JPG" /path/to/source/$file #otherwise the file renamed as file.JPG so it is not overwritten
    fi 
done 

任何人都可以帮我处理这段代码吗?我正在尝试在 Bash 中编写一个脚本,它将为目录中的所有文件生成哈希,如果有两个重复的哈希,那么只有一个图像被复制到目标目录,任何人都可以看到我哪里出错了这里?

我必须使用 md5sum,所以不幸的是没有其他 sha1s、fdupes 或类似的东西。

4

1 回答 1

2

假设复制哪个唯一文件无关紧要,一种简单的方法是使用 bash 对关联数组的支持:

declare -A files

while read hash name
do
    files[$hash]=$name
done < <(md5sum /path/to/source/*)

cp "${files[@]}" /path/to/dest

任何具有相同哈希值的文件都将简单地覆盖前一个文件的记录,从而在数组中只留下唯一的文件。

于 2013-11-26T22:08:44.420 回答