I am a pretty new to programming or scripting. Please help me in my below query.
I want to write a script which can track a file for any kind of modification and if there is any modification then it should move that file or i should say backup that file to another server.
#!/bin/sh
file="/path/to/file"
destdir="/dest/dir"
if [ ! -e $file ]; then
echo "file $file not present"
exit 1;
fi
l=$(stat -f %Sm $file)
while true; do
c=$(stat -f %Sm $file 2>/dev/null)
if [ "$l" != "$c" ]; then
mv "$file" $destdir 2>/dev/null
fi
sleep 5
if [ ! -e $file ]; then
echo "file $file not present, waiting for $file..."
fi
done
Not exactly.. actually file would be always there but I want to copy it only when somebody change it. And one more thing I need to copy file on different server.
sorry if it sounds a stupid query but I am from networking so dont know much about unix stuff.
How rsync would work, will it be running in background tracking and watching one file for any kind of modification?
You will have to go through the documentation to tweak for your exact requirements. But here is a sample command that I use to keep my profile and settings in sync across multiple home directories (across multiple servers):
##
## Update the following variables as per your settings.
##
## Path of the rsync utility on the remote server
RSYNC_PATH=/path/to/rsync
## List of files to be backed up every time something changes
FILE_LIST="$home/.profile $home/.functions $home/.vimrc $home/install"
## Remote server
REMOTE_SERVER=my_backup_server
## Remote path where to put the backup files
REMOTE_BACKUP_PATH=/my/backup/path
rsync --links --recursive --rsync-path=$RSYNC_PATH --verbose \
$FILE_LIST $REMOTE_SERVER:$REMOTE_BACKUP_PATH
Note that before this can be used, you will have to make sure that rsync is installed on both local and the remote server.
You can put this in a script and schedule it in the cron to run on a set frequency based on how often you expect your files to get changed.