MySQL 备份
Automated MySQL Database Backup
Version 1
Want to backup your MySQL databases to another machine on a nightly basis?
Then create a /etc/cron.daily/mysqlbackup.sh job like this:
Run chmod +x /etc/cron.daily/mysqlbackup.sh
. And change the $ parameters to the appropriate 'real' values.
Or if you are not backing up to a separate host, run:
Version 2
This one is slightly more advanced. It's a bash script that will basically do the same as above but also only keep a certain number of old copies.
Note that this script is prepared to backup as the root user, if you are going to be running this as a non root user you should modify paths to reflect that.
# List of databases to be backed up separated by space
dblist="db_name_1 db_name_2 db_name_3 etc."
# Directory for backups
backupdir=/root/mysql_dumps
# Number of versions to keep
numversions=4
# Full path for MySQL hotcopy command
# Please put credentials into /root/.my.cnf
#hotcopycmd=/usr/bin/mysqlhotcopy
hotcopycmd="/usr/bin/mysqldump --lock-tables --databases"
# Create directory if needed
mkdir -p "$backupdir"
if [ ! -d "$backupdir" ]; then
echo "Invalid directory: $backupdir"
exit 1
fi
# Hotcopy begins here
echo "Dumping MySQL Databases..."
RC=0
for database in $dblist; do
echo
echo "Dumping $database ..."
mv "$backupdir/$database.gz" "$backupdir/$database.0.gz" 2> /dev/null
$hotcopycmd $database | gzip > "$backupdir/$database.gz"
RC=$?
if [ $RC -gt 0 ]; then
continue;
fi
# Rollover the backup directories
rm -fr "$backupdir/$database.$numversions.gz" 2> /dev/null
i=$numversions
while [ $i -gt 0 ]; do
mv "$backupdir/$database.`expr $i - 1`.gz" "$backupdir/$database.$i.gz" 2> /dev/null
i=`expr $i - 1`
done
done
if [ $RC -gt 0 ]; then
echo "MySQL Dump failed!"
exit $RC
else
# Hotcopy is complete. List the backup versions!
ls -l "$backupdir"
echo "MySQL Dump is complete!"
fi
exit 0
So this system has three parts. First is the file that holds the credentials, e.g. /root/.my.cnf and it's in standard mysql config format like so:
Second is the script itself, as listed above. Enter the names of your dbs, how many copies to keep, and where to put them.
Third is the crontab entry that will run this script for you. For example, once per day:
# ----------------- minute (0 - 59)
# | -------------- hour (0 - 23)
# | | ----------- day of month (1 - 31)
# | | | -------- month (1 - 12)
# | | | | ----- day of week (0 - 7) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
35 01 * * * /root/mysql_backup.sh
完!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理