WhereAreYouSyntax
WhereAreYouSyntax

Reputation: 163

Md5 Hash to identify and archive images

This is my first ever bash script and I am trying to iron out all of the creases and make the script run nicely. The script is to archive all of the specified .jpg files that it finds in multiple directories on a HDD/Flash drive. There are files with the same name but different content so I have used an Md5 sum to hash them.

I am getting the directory does not exist error in Geany but it runs fine from command bar missing out two of the images. I have tried everything I can think of to fix it. Is it messy code that is doing this?

#!/bin/sh

if [ ! -d "$1" ]; then
    echo Directory "$1" cannot be found. Please try again.
    exit
fi

if [ $# -eq 1  ]; then
    echo "usage: Phar image_path archive_path"
    exit
fi

if [ -d "$2" ]; then
    echo "archive exists"
else
    echo "the directory 'archive' does't exist. Creating directory 'archive'."
    mkdir -p ~/archive 
fi

find $1 -iname "IMG_[0-9][0-9][0-9][0-9].JPG" | cat > list.txt

[ -f ~/my-documents/md5.txt ] && rm md5.txt || break 
while read line;
    do md5sum $line | xargs >> md5.txt 
done < list.txt 

sort -k 1,1 -u md5.txt | cat > uniquemd5.txt 
cut -d " " -f 2- uniquemd5.txt > uniquelist.txt 

sort uniquelist.txt -r -o uniquelist.txt
for line in $(cat uniquelist.txt)
do
    file=$(basename $line) path="$2/file"

    if [ ! -f $path ];
    then 
        cp $line $2 
else
        cp $line $path.JPG


  fi

done

Upvotes: 0

Views: 640

Answers (1)

CodeReaper
CodeReaper

Reputation: 6145

You haven't guarded against spaces in the folder and file names everywhere.

For instance:

cp $line $2 

should be:

cp "$line" "$2"

You should start by eliminating these spaces as a source to your error by evaluating each variable you are referencing and adding ""'s.

If you still get the error please provide us with the arguments used and which directory that does not exist.

Upvotes: 1

Related Questions