Moving multiple files in directory that have dupli

2019-09-03 08:25发布

问题:

This question already has an answer here:

  • Moving multiple files in directory that might have duplicate file names 2 answers

can anyone help me with this?

I am trying to copy images from my USB to an archive on my computer, I have decided to make a BASH script to make this job easier. I want to copy files(ie IMG_0101.JPG) and if there is already a file with that name in the archive (Which there will be as I wipe my camera everytime I use it) the file should be named IMG_0101.JPG.JPG so that I don't lose the file.

#!/bin/bash

if [ $# -eq 0 ] 
then 
echo "Usage: $0 image_path archive_path"
exit 999
fi

if [ -d "$1" ] #Checks if archive directory exists
then
echo Image Source directory FOUND
else
echo ERROR: Image Source directory has NOT BEEN FOUND
fi

if [ -d "$2" ]
then
echo Photo Archive FOUND
else
echo Creating directory
mkdir "$2"
fi 

    if [ find $1 -name "IMG_[0-9][0-9][0-9][0-9].JPG" ] #added this in to be more specific 1/4
    then #2/4
        for file in "$1"/*
        do

        dupefile= "$2"/"$file"
            while [ -e "$newfile" ];
            do
            newfile=$newfile.JPG
            done
        mv "$file" "$newfile"
        done
    else #3/4
    #do nothing
    fi #4/4 took all the /4 out, but it's saying theres no such file or directory, even though I've tested it and it says there is. 

unexpected token fi is the error I'm getting but the if statement needs to be in there so the specific files i need, are getting moved.

回答1:

You cannot have an empty else. Take out the else keyword if you don't have an else part.

Also, you should get rid of the superfluous find. Just loop over the files you actually want instead.

for file in "$1"/IMG_[0-9][0-9][0-9][0-9].JPG
do
    newfile= "$2"/"$file"
    while [ -e "$newfile" ];
    do
        newfile=$newfile.JPG
    done
    mv "$file" "$newfile"
    done
done

(This also addresses the dupefile vs newfile error.)