Perl Script to Backup MySQL Databases

Written by BinnyVA on June 19, 2008 – 11:13 pm -

So far, we covered backing up files locally and over a network. Now let let see how to backup databases(only mysql supported – yet).

The script uses ‘mysqldump’ command to backup the data. That means that the backups are in the SQL dump format. The dumps of all the databases that are backed up are compressed and stored in the destination folder. They will be named in this format – YYYY-MM-DD.tar.gz.

Configuration File

This script reads a configuration file named ‘dbbackup.config’ and backups all the databases specified in that file to another location in the same system. This configuration file must be in the same folder as the perl script. The configuration file format is given below…

# Unwanted_DB - commented - will not be backedup

The Perl Script

# Backups all the databases specified in the dbbackup.config file

$backup_folder = '/var/Backup/Special/Databases'; #EDIT THIS LINE

use File::Basename;
my $config_file = dirname($0) . "/dbbackup.config";
my @databases = removeComments(getFileContents($config_file));

chdir($backup_folder) or die("Cannot go to folder '$backup_folder'");

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$year += 1900;
#Zero padding
$mday = '0'.$mday if ($mday<10);
$mon = '0'.$mon if ($mon<10);

my $folder = "$year-$mon-$mday";
mkdir($folder) or die("Cannot create a folder called '$folder'");

foreach my $database (@databases) {
	next if ($database eq '');
	my $table = '';
	if(index($database,' ')+1) { #Get just 1 table in the database - if there is a ' '(space) in the db name
		my @parts = split(' ',$database);
		$database = $parts[0];
		$table = $parts[1];
	print "Backing up $database ... ";

 	my $file = $database;
 	$file .= '_' . $table if($table ne '');
 	$file .= ".sql";
 	`mysqldump -u root $database $table > $folder/$file`;

	print "Done\n";
print "Compressing the folder ... ";
`tar -czf $folder.tar.gz $folder/`;
print "Done\nRemoving Folder ... ";
`rm -rf $folder`;
print "Done\n\n";

sub getFileContents {
	my $file = shift;
	open (FILE,$file) || die("Can't open '$file': $!");
	my @lines=<FILE>;
	return @lines;

sub removeComments {
	my @lines = @_;

	@cleaned = grep(!/^\s*#/, @lines); #Remove Comments
	@cleaned = grep(!/^\s*$/, @cleaned); #Remove Empty lines

	return @cleaned;

If you need, you can set this script as a cron job – this will make sure that you don’t have to worry about the backup.

Tags: , , , ,
Posted in Programming, Scripting, Shell Scripts | 17 Comments »