perl初心者BLOG

2011-01-11

[]MySQLのバックアップスクリプトを書いてみた 23:31

#!/usr/bin/perl
use strict;
use warnings;
use File::Path;

#
# Define
#

my $owner = "user1";
chop(my $user = `whoami`);
my $tmp_dir = "/home/$owner/tmp.mysql_backup.$$/";
my $mysqldump = "/home/mysql/bin/mysqldump";
chop(my $current_time = `date +%Y%m%d.%H%M%S`);
my $dump_file_name = "dump.sql";
my $tgz_file_name = "mysql." . $current_time . ".tgz";
my $tgz_dir = "/tmp/";
my $tgz_file_path = "${tgz_dir}${tgz_file_name}";


#
# Check
#

if ($owner ne $user) {
	die("You aren't the user $owner. If you want to change the user, you should edit this script.");
}

if (-e $tmp_dir) {
	die("The directory $tmp_dir is already exists.  Perhaps, this script has a problem.");
}

if (! -e $tgz_dir) {
	die("The directory $tgz_dir is not exists. You should make the directory.");
}


#
# Init
#

if (!mkdir($tmp_dir)) {
	die("The function mkdir is failed. The directory is $tmp_dir.");
}


#
# Do mysqldump
#
my $cmd = "$mysqldump -u mysql -pXXX -A -F --opt --quick --default-character-set=binary > ${tmp_dir}${dump_file_name}";
print "$cmd\n";
`$cmd`;


#
# Do compress
#

$cmd = "tar czvpf $tgz_file_path -C $tmp_dir $dump_file_name";
print "$cmd\n";
`$cmd`;


#
# Terminate
#

print "Remove the directory $tmp_dir\n";
my $num = rmtree($tmp_dir);