MySQL备份和删除旧备份

时间:2015-09-21 12:49:07

标签: mysql linux bash shell centos

我使用以下简单脚本通过tar备份我的所有数据库,而不是删除7天之前的旧备份目录(包括其中的文件),因此它不会占用所有空间

#!/bin/bash
# Simple script to backup MySQL databases

# Parent backup directory
backup_parent_dir="/backup/mysql"

# MySQL settings
mysql_user="root"
mysql_password="mypass"
mysql_server="localhost"

# Read MySQL password from stdin if empty
if [ -z "${mysql_password}" ]; then
  echo -n "Enter MySQL ${mysql_user} password: "
  read -s mysql_password
  echo
fi

# Check MySQL password
echo exit | mysql --host=${mysql_server} --user=${mysql_user} --password=${mysql_password} -B 2>/dev/null
if [ "$?" -gt 0 ]; then
  echo "MySQL ${mysql_user} password incorrect"
  exit 1
else
  echo "MySQL ${mysql_user} password correct."
fi

# Create backup directory and set permissions
backup_date=`date +%Y_%m_%d_%H_%M`
backup_dir="${backup_parent_dir}/${backup_date}"
echo "Backup directory: ${backup_dir}"
mkdir -p "${backup_dir}"
chmod 755 "${backup_dir}"

# Get MySQL databases
mysql_databases=`echo 'show databases' | mysql --host=${mysql_server} --user=${mysql_user} --password=${mysql_password} -B | sed /^Database$/d`

# Backup and compress each database
for database in $mysql_databases
do
  if [ "${database}" == "information_schema" ] || [ "${database}" == "performance_schema" ]; then
        additional_mysqldump_params="--skip-lock-tables"
  else
        additional_mysqldump_params=""
  fi
  echo "Creating backup of \"${database}\" database"
  mysqldump ${additional_mysqldump_params} --host=${mysql_server} --user=${mysql_user} --password=${mysql_password} ${database} | gzip > "${backup_dir}/${database}.gz"
  chmod 600 "${backup_dir}/${database}.gz"
done

#Delete backups older than 7 days
find ${backup_parent_dir} -name '*' -type d -mtime +6 -exec rm -rfv "{}" \;

现在,备份工作正常,它将所有数据库备份到单独的目录中,但由于某种原因,它不会通过此部分删除旧的备份目录

#Delete backups older than 7 days
find ${backup_parent_dir} -name '*' -type d -mtime +6 -exec rm -rfv "{}" \;

但是,如果我运行一个单独的脚本,它只包含以下代码而不是完全正常工作并删除所有7天的旧目录

# Parent backup directory
backup_parent_dir="/backup/mysql"

#Delete backups older than 7 days
find ${backup_parent_dir} -name '*' -type d -mtime +6 -exec rm -rfv "{}" \;

所以,我不确定为什么删除行在添加到单个脚本中时不起作用?

1 个答案:

答案 0 :(得分:0)

我建议执行这样的脚本,这将打印有关脚本每个步骤的更多信息

bash -x nameofscript

也是出于调试原因而不是

find ${backup_parent_dir} -name '*' -type d -mtime +6 -exec rm -rfv "{}" \;

使用

find ${backup_parent_dir} -name '*' -type d -mtime +6

只是为了看哪些会被删除