search
HomeDatabaseMysql Tutoriallinux中mysql备份,增量备份及恢复程序

一个linux中mysql完全备份,增量备份及恢复脚本实现程序,有需要的朋友可参考一下,可以把它做成定时备份哦。

 代码如下 复制代码

#!/bin/bash
# full && increment backup and recover
# 说明:事先要确保存在/data/bak目录,且要保证在执行增量备份时已做过至少一次全量备份,否则找不到position文件。
port='3306'
back_src_dir="/data/mysql/${port}/logs/binlog"
back_dir='/data/bak'
DATE=`date +%Y%m%d`
user='root'
pass='cy2009'
bak_db='test1'
mysql_bin='/usr/local/mysql-5.1.48/bin'
socket="/data/mysql/${port}/mysql.sock"
full_bak()
{
cd ${back_dir}
DumpFile=Full_back$DATE.sql
${mysql_bin}/mysqldump --lock-all-tables --flush-logs --master-data=2 -u${user} -p${pass} ${bak_db} > ${DumpFile}
${mysql_bin}/mysql -u${user} -p${pass} --socket=${socket} -e "unlock tables"

#把当前的binlog和position信息存入position文件
cat ${DumpFile} |grep 'MASTER_LOG_FILE'|awk -F"'" '{print $2}' > ${back_dir}/position
cat ${DumpFile} |grep 'MASTER_LOG_FILE'|awk -F"=" '{print $3}' |awk -F";" '{print $1}' >> ${back_dir}/position
}
incre_bak()
{
#锁定表,刷新log
${mysql_bin}/mysql -u${user} -p${pass} --socket=${socket} -e "flush tables with read lock"
${mysql_bin}/mysqladmin -u${user} -p${pass} --socket=${socket} flush-logs
#获取上次备份完成时的binlog和position
cd ${back_dir}
start_binlog=`sed -n '1p' position`
start_pos=`sed -n '2p' position`

#获取目前的binlog和position
mysql -u${user} -p${pass} --socket=${socket} -e "show master statusG" | awk '{print $2}'| sed -n '2,3p' > now_position
stop_binlog=`sed -n '1p' now_position`
stop_pos=`sed -n '2p' now_position`
#如果在同一个binlog中
if [ "${start_binlog}" == "${stop_binlog}" ]; then
${mysql_bin}/mysqlbinlog --start-position=${start_pos} --stop-position=${stop_pos} ${back_src_dir}/${start_binlog} >> Incr_back$DATE.sql

#跨binlog备份
else
startline=`awk "/${start_binlog}/{print NR}" ${back_src_dir}/mysql-bin.index`
stopline=`wc -l ${back_src_dir}/mysql-bin.index |awk '{print $1}'`
for i in `seq ${startline} ${stopline}`
do
binlog=`sed -n "$i"p ${back_src_dir}/mysql-bin.index |sed 's/.*///g'`
case "${binlog}" in
"${start_binlog}")
${mysql_bin}/mysqlbinlog --start-position=${start_pos} ${back_src_dir}/${binlog} >> Incr_back$DATE.sql
;;
"${stop_binlog}")
${mysql_bin}/mysqlbinlog --stop-position=${stop_pos} ${back_src_dir}/${binlog} >> Incr_back$DATE.sql
;;
*)
${mysql_bin}/mysqlbinlog ${back_src_dir}/${binlog} >> Incr_back$DATE.sql
;;
esac
done
fi
#解除表锁定,并保存目前的binlog和position信息到position文件。
${mysql_bin}/mysql -u${user} -p${pass} --socket=${socket} -e "unlock tables"
cp now_position position
}
full_recov()
{
cd ${back_dir}
recov_file1=`ls | grep 'Full_back'`
${mysql_bin}/mysql -u${user} -p${pass} --socket=${socket} -e "use ${bak_db}; source ${back_dir}/${recov_file1};"
}

incre_recov()
{
cd ${back_dir}
recov_file2=`ls |grep 'Incr_back'`
${mysql_bin}/mysql -u${user} -p${pass} --socket=${socket} -e "use ${bak_db}; source ${back_dir}/${recov_file2};"
}
while true
do
echo -e "tt**************************************"
echo
echo -e "tttWelcome to backup program!"
echo
echo -e "ttt(1) Full Backup For MySQL"
echo -e "ttt(2) Increment Backup For MySQL"
echo -e "ttt(3) Recover From The Full Backup File"
echo -e "ttt(4) Recover From The Increment Backup File"
echo -e "ttt(5) Exit The Program!"
echo
echo -e "tt**************************************"
read -p "Enter your choice:" choice
case $choice in
)
echo "now! let's backup the data by full method......."
full_bak
echo "succeed!"
sleep 2
;;
)
echo "now! let's backup the data by increment method......"
incre_bak
echo "succeed"
sleep 2
;;
)
echo "now! let's recover from the full back file"
full_recov
echo "successful"
sleep 2
;;
)
echo "now! let's recover from the increment backup file"
incre_recov
echo "successful"
sleep 2
;;
)
break
;;
*)
echo "Wrong Option! try again!"
sleep 2
continue
;;
esac
done

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

MySQL: How to Add a User RemotelyMySQL: How to Add a User RemotelyMay 12, 2025 am 12:10 AM

ToaddauserremotelytoMySQL,followthesesteps:1)ConnecttoMySQLasroot,2)Createanewuserwithremoteaccess,3)Grantnecessaryprivileges,and4)Flushprivileges.BecautiousofsecurityrisksbylimitingprivilegesandaccesstospecificIPs,ensuringstrongpasswords,andmonitori

The Ultimate Guide to MySQL String Data Types: Efficient Data StorageThe Ultimate Guide to MySQL String Data Types: Efficient Data StorageMay 12, 2025 am 12:05 AM

TostorestringsefficientlyinMySQL,choosetherightdatatypebasedonyourneeds:1)UseCHARforfixed-lengthstringslikecountrycodes.2)UseVARCHARforvariable-lengthstringslikenames.3)UseTEXTforlong-formtextcontent.4)UseBLOBforbinarydatalikeimages.Considerstorageov

MySQL BLOB vs. TEXT: Choosing the Right Data Type for Large ObjectsMySQL BLOB vs. TEXT: Choosing the Right Data Type for Large ObjectsMay 11, 2025 am 12:13 AM

When selecting MySQL's BLOB and TEXT data types, BLOB is suitable for storing binary data, and TEXT is suitable for storing text data. 1) BLOB is suitable for binary data such as pictures and audio, 2) TEXT is suitable for text data such as articles and comments. When choosing, data properties and performance optimization must be considered.

MySQL: Should I use root user for my product?MySQL: Should I use root user for my product?May 11, 2025 am 12:11 AM

No,youshouldnotusetherootuserinMySQLforyourproduct.Instead,createspecificuserswithlimitedprivilegestoenhancesecurityandperformance:1)Createanewuserwithastrongpassword,2)Grantonlynecessarypermissionstothisuser,3)Regularlyreviewandupdateuserpermissions

MySQL String Data Types Explained: Choosing the Right Type for Your DataMySQL String Data Types Explained: Choosing the Right Type for Your DataMay 11, 2025 am 12:10 AM

MySQLstringdatatypesshouldbechosenbasedondatacharacteristicsandusecases:1)UseCHARforfixed-lengthstringslikecountrycodes.2)UseVARCHARforvariable-lengthstringslikenames.3)UseBINARYorVARBINARYforbinarydatalikecryptographickeys.4)UseBLOBorTEXTforlargeuns

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft