Your if [ "$file_hash" == "$a" ];
compares a hash with a filename. You need something like
if [ "$file_hash" == $(md5sum "$a" | cut -d ' ' -f 1) ];
to compute the hash for each of the file in destination folder.
Furthermore, your for loop, in its current version, runs only once ; you need something like
for a in $destination_folder/*
to get all files in that folder rather than just the folder name.
Based on your edits, a solution would look like
#!/bin/bash -xv
file=$1
destination_folder=$2
file_hash=`md5sum "$file" | cut -d ' ' -f 1`
# test that the filename exists in the destination dir
if [[ -f $destination_folder/$file ]] ; then
dest_hash=$(md5sum "$destination_folder/$file" | cut -d ' ' -f 1)
# test that the hash is the same
if [[ "$file_hash" == $curr_hash ]] ; then
cp "$file.JPG" "$destination_folder/$file.JPG"
else
# do nothing
fi
else
# destination does not exit, copy file
cp "$file.JPG" "$destination_folder/$file"
fi
This does not ensure that there are no duplicates. It simply ensures that distinct files with identical names do not overwrite each other.
#!/bin/bash -xv
file=$1
destination_folder=$2
file_hash=`md5sum "$file" | cut -d ' ' -f 1`
# test each file in destination
for a in $destination_folder/*
do
curr_hash=$(md5sum "$a" | cut -d ' ' -f 1)
if [ "$file_hash" == $curr_hash ];
then
# an identical file exists. (maybe under another name)
# do nothing
exists=1
break
fi
done
if [[ $exists != 1 ]] ; then
if [[ -f $destination_folder/$file ]] ; then
cp "$file.JPG" "$destination_folder/$file.JPG"
else
cp "$file.JPG" "$destination_folder"
fi
fi
Not tested.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…