Backup and Restore With Linux
Moving updated files from one server to another server can be done with few Linux commands. To move or backup files to another server, you could create a tar or zip file on one server. Then, you can use SCP to move the tar or zip file to the foreign server. After it reaches its destination, you extract it.
From a backup point of view, it only makes sense to backup the folder to a new server when the files change. In this case, you can run a cron job that checks for file modification, and only creates and sends the backup when there are updated files. You could make this check at any desired interval that you want; from hourly to daily to weekly.
The server which will store the backups can have a cron job that checks for a new backup tar or zip file within a specific directory. Then, if its date is within a specified time interval, you can run a command to extract the tar or zip file.
Make the Backup on Host Machine
The one-liner below shows how to check and make a backup tar ball for all of the new files within 1 day.
root# find /home/username/public_html/foldername -type f -mtime -1 | xargs tar -czf foldername.tar
Moving tar file to New Server
root# scp -P 22 /home/username/Desktop/foldername.tar firstname.lastname@example.org:/home/username/public_html/foldername.tar
Restore the Backup On Slave Machine
The line below shows how to extract the tar file from the machine which stores the backups. It will only overwrite the old files which have been modified and leave the rest intact.
root# tar -xvf foldername.tar
Alternatively, you could run the following code with a cron job. It will look for the file to see if it is less than 1 day old. If it is, the tar file is extracted. If it is not, output is redirected to the black hole ‘> /dev/null 2>&1’. With this bash command, the find command is run. After that, the ‘&&’ operator represents the if statement and the ‘||’ operator represents the else statement.
root# [ `find /home/username/public_html/foldername.tar -type f -mtime -1` ] && tar -xvf /home/username/public_html/foldername.tar || echo "File is within 1 day"
root# [ `find /home/username/public_html/foldername.tar -type f -mtime -1` ] && tar -xvf /home/username/public_html/foldername.tar || > /dev/null 2>&1
One more method to check the file created date and extract it if it is within 1 day old is shown below. This technique uses a single command. It looks for the file that was created within one day, then runs the ‘-exec’ action which is another linux command.
root# find /home/username/public_html/foldername.tar -type f -mtime -1 -exec tar -xvf /home/username/public_html/foldername.tar \;
The steps above can be used to backup and move new files. But, to do it automatically, you need to run cron jobs that use these commands as bash scripts. Also, you need to use SSH keys to transfer the files via SCP without a password or the transfer will not happen.