Hello there -

I have three directories. I would like to compare directory1 with directory2, then take those changes/new files and copy them over to directory3. I was given the following code:

#!/bin/bash

dir2="d1"
dir1="d2"
dir3="d3"

for file in dir2/*; do
    file_in_dir1=dir1/$(basename ${file})
    if [ ! -e  ${file_in_dir1} ]; then
        # If the file in dir2 does not exist in dir1, copy
        cp ${file} dir3
    elif ! diff ${file} ${file_in_dir1}; then
        # if the file in dir2 is different then the one in dir1, copy
        cp ${file} dir3
    fi
done

And I'm getting the following error: 7: Syntax error: word unexpected (expecting "do")

I don't have any experience in shell scripting. Can someone tell me what I need to do to get this script working...

Thanks!
Andrew

Hello,

I think the error is because you are missing the $ in front of dir2/* and anywhere else you are referencing the variables dir1 dir2 dir3. The only line that should not have the $ is the initial definition when you set them to d1, d2 and d3 respectively.

It would look like this:

#!/bin/bash

dir2="d1"
dir1="d2"
dir3="d3"

for file in $dir2/*; do
    file_in_dir1=$dir1/$(basename ${file})
    if [ ! -e  ${file_in_dir1} ]; then
        # If the file in dir2 does not exist in dir1, copy
        cp ${file} $dir3
    elif ! diff ${file} ${file_in_dir1}; then
        # if the file in dir2 is different then the one in dir1, copy
        cp ${file} $dir3
    fi
done

But that is still off a little in the second test. Also this only tests to see if a there is a new file in d2 that is not in d1. What about new files in d1 not in d2?

You might be able to use the following command to get what is different in the directories and then copy the files.

diff -qr d1 d2
commented: good to mention diff -qr +1

Hello -

Still get the same error. Your 2nd example won't work either because it doesn't copy anything over to a 3rd directory. Regarding new files in d1, I don't need them. d1 will always be an out-of-date structure and if they no longer exists in d2, they were removed.

Thank,
Andrew

Andrew,
OK how about this then:

#!/bin/bash
DIR1=d1
DIR2=d2
DIR3=d3
for x in `/bin/ls $DIR2 `
do 
	#If the file does not exits in DIR3 then copy it.
	if [ ! -a $DIR3/$x ]
	then /bin/cp $DIR2/$x $DIR3/
	fi
	# If the file exists in DIR3 but one in DIR2 is newer copy it.
	if [ $DIR2/$x -nt $DIR3/$x ]
	then /bin/cp $DIR2/$x $DIR3/
	fi
done
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.