Sometimes, when you writing code you make a lot of mistakes and you want to go back to a previous version, but you don’t have one. It’s recommended that you always back-up your data.
I tried a lot of back-up solutions, but they didn’t satisfy what I need. I need to make a backup to a certain moment and to have permission to read data.
So, I started to write a simple backup program. Here it is:
First, we need to write a Perl script which will tar and gzip some data and also write to a log file
!# /usr/bin/perl
print “Starting..n”;
($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
$year=1900+$yearOffset;
$x=int(rand(100));
$time=”$year-$month-$dayOfMonth-$hour$minute$second”;
open (FILE, “>>”, “$ARGV[0]-backup.log”);
print FILE “Start back-up $timen”;
&run(“tar -cf $ARGV[0]-$time.tar $ARGV[1]”);
&run(“gzip $ARGV[0]-$time.tar”);
&run(“chmod 777 $ARGV[0]-$time.tar.gz”);
print FILE “Finished back-up $timenn “;
close (FILE);
print “Finished!nn”;
sub run(){
# print “”;
@args = ($_[0]);
system(@args) == 0 or die “system @args failed: $?”;if ($? == -1) {
1;
print “failed to execute: $!n”;
}
elsif ($? & 127) {
printf “child died with signal %d, %s coredumpn”,
($? & 127), ($? & 128) ? ‘with’ : ‘without’;
}
else {
#printf “child exited with value %dn”, $? >> 8;
}
}
After this we need a bash file which will be a cronjob
#!/bin/bash
echo -n “Running backup.cgi”
cd $(dirname $0)
perl $(dirname $0)/backup.cgi $@
exit 0
Copy those scripts to a directory and chmod 755 them to be executable:
chmod 755 backup.cgi chmod 755 backup.sh
Finally, we add those cron jobs. Because I need to backup some files that my user don’t have permission I insert those cron jobs into root’s crontab:
# crontab -e 0 * * * * /home/adrian/backup/backup.sh apache /srv/www
15 * * * * /home/adrian/backup/backup.sh apache /srv/www
30 * * * * /home/adrian/backup/backup.sh apache /srv/www
45 * * * * /home/adrian/backup/backup.sh apache /srv/www
0 * * * * /home/adrian/backup/backup.sh mysql /var/lib/mysq
This will backup the content of Apache server every 15 minutes and the MySQL databases every hour.
The syntax for crontab is the following:
.—————- minute (0 – 59) | .————- hour (0 – 23) | | .———- day of month (1 – 31) | | | .——- month (1 – 12) OR jan,feb,mar,apr … | | | | .—- day of week (0 – 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat | | | | | * * * * * command to be executed > file_where_to_write_outputI hope you find useful this program!
echo -n “Running backup.cgi”
cd $(dirname $0)
perl $(dirname $0)/backup.cgi $@
exit 0