Checking of file exist in different folder

Hi All,

Seeking for your assistance to compare if the file in working directory is found on the DIR2 directory and if not found move the file in DIR2.

ex. WORKING_DIR=/home/dir1/
file1.txt

DIR2=/home/admin/users
file1.txt

what i did was

found_nonempty=''
  for file in $WORKING_DIR* ; do
    if [[ -s "$file" ]] ; then
      found_nonempty=1
    fi
  done
  if [[ "$found_nonempty" ]] ; then
    echo found one
  else
    echo found none
  fi

but this was only to check if file exist in current directory.

Please advise,

Thanks,

---------- Post updated at 10:27 AM ---------- Previous update was at 08:35 AM ----------

i now solved the issue. thx :slight_smile:

I do not understand what you are trying to do.

Your stated goal:

doesn't say anything about file sizes (which is all that the code snippet you have shown us tests).

If a file found in $DIR2 and is not found in $WORKING_DIR , what do you want to happen?

If a file is present in $WORKING_DIR that is not found in $DIR2 , is anything supposed to happen? If so, what?

Does the size of the file make any difference in what is supposed to happen if a file is found in one of these two directories and not in the other? If so, what?

This is what i done Mod.

WORKING_DIR=/home/working_dir
DIR2=/home/target_dir

#check if there's a zip file in the WORKING_DIR
if [ "`ls -A $WORKING_DIR/*.ZIP 2>/dev/null`" ]
then
echo "contains files (or is a file)"
cd $WORKING_DIR
        for i in *.ZIP
                do
                        a=$(find $DIR2 -iname "$i" -print | wc -l) -- i used find command to check if there's a file in $DIR2 equals to $i and count
                        if [[ $a > 0 ]]; then
                                 echo "File Exist in $DIR2"
                        else
                                 echo "File Not Exist in $DIR2"
                                 echo "Copying $i to $DIR2"
                        cp $i $DIR2
        fi
done
else
echo "No such file in the Directory"
fi

Hope it helps :slight_smile:

Thanks,

Assuming that filenames are identical if they exist in both directories (i.e., no case differences), you might find the following to be more concise and more efficient in terms of CPU and disk usage:

#!/bin/ksh
WORKING_DIR=/home/working_dir
DIR2=/home/target_dir

cd $WORKING_DIR
for i in *.[Zz][Ii][Pp]
do	if [ "$i" = "*.[Zz][Ii][Pp]" ]
	then	echo "No such file in the Directory"
		exit
	fi
	if [ -f "$DIR2/$i" ]
	then	echo "File $i Exist in $DIR2"
	else	echo "File $i Not Exist in $DIR2"
		echo "Copying $i to $DIR2"
		cp "$i" "$DIR2"
        fi
done

I used the Korn shell for testing this (you didn't say what shell you're using), but this should work with any shell that follows basic Bourne shell syntax.

I think this should do it:

rsync --ignore-existing $WORKING_DIR $DIR2

I didn't test it, so please try it with the option -n first (this would show what is copied, without actually copying anything).