Beginner/Intermediate shell; comfortable in the command line.
I have been looking for a solution to a backup problem. I need to compare Directory 1 to Directory 2 and copy all modified or new files/directories from Directory 1 to Directory 3. I need the directory and file structure to be mirrored on Directory 3. Another way of thinking about the logic is: Dir1 - Dir2 = Dir3. I want Dir3 to be portable between users/machines so I don't think an incremental backup with hardlinks will work. Seems like it should be easy right?
I found a scripts that seems like it could do the trick. However, I'm having some trouble getting it to work properly. It compares Dir1 to Dir2 and copies all new or modified files into Dir3 but it does NOT recreate the directory structure on the target. Instead all files end up in a flat folder.
From Statckoverflow . com
#!/bin/bash
#
# setup folders for our different stages
#
Dir1=/Users/username/source1
Dir2=/Users/username/source2
Dir3=/Users/username/target
#
cd $Dir1
for f in *f
do
# Diff the files - ignore the output...
diff $f $Dir2 > /dev/null 2>&1
# ...but get the status
status=$?
if [ $status -eq 0 ] ; then
# Files are identical - don't copy the file
echo $f unchanged
elif [ $status -eq 1 ] ; then
# Files differ - copy new file
echo $f changed
cp $f $diff
elif [ $status -eq 2 ] ; then
# Old file doesn't exist - copy new file
echo old $f does not exist
cp $f $diff
fi
done
I started my reading with rsync. I've used it for back up - locally and over ssh between NAS servers. It should be able to do the job, right? I just couldn't find examples to guide me and I don't know enough and / or have enough time to do it unaided. Researching it I got side tracked by diff which I didn't know much about but it looked promising.
My preference is to do this with a bash script. Anyone have any ideas?
Thanks!