search
HomeDatabaseMysql TutorialLinux Shell脚本之利用mysqldump备份MySQL数据库(详细注解)

利用mysqldump命令备份MySQL数据库的脚本(不带注释版,适合生产环境使用)

设计该脚本的一些设计、编写考虑:

利用mysqldump命令备份MySQL数据库的脚本(不带注释版,适合生产环境使用)

#!/bin/bash
MYSQLDBUSERNAME=root
MYSQLDBPASSWORD=password
MYSQBASEDIR=/usr/local/mysql
MYSQL=$MYSQBASEDIR/bin/mysql
MYSQLDUMP=$MYSQBASEDIR/bin/mysqldump
BACKDIR=/var/backup/db
DATEFORMATTYPE1=$(date +%Y-%m-%d)
DATEFORMATTYPE2=$(date +%Y%m%d%H%M%S)
[ -d $MYSQBASEDIR ] && MYSQDATADIR=$MYSQBASEDIR/data || MYSQDATADIR=/var/lib/mysql
[ -x $MYSQL ] || MYSQL=mysql
[ -x $MYSQLDUMP ] || MYSQLDUMP=mysqldump
[ -d ${BACKDIR} ] || mkdir -p ${BACKDIR}
[ -d ${BACKDIR}/${DATEFORMATTYPE1} ] || mkdir ${BACKDIR}/${DATEFORMATTYPE1}
DBLIST=`ls -p $MYSQDATADIR | grep / |tr -d /`
for DBNAME in $DBLIST
    do ${MYSQLDUMP} --user=${MYSQLDBUSERNAME} --password=${MYSQLDBPASSWORD} --routines --events --triggers --single-transaction --flush-logs --databases ${DBNAME} | gzip > ${BACKDIR}/${DATEFORMATTYPE1}/${DBNAME}-backup-${DATEFORMATTYPE2}.sql.gz
    [ $? -eq 0 ] && echo "${DBNAME} has been backuped successful" || echo "${DBNAME} has been backuped failed"
    /bin/sleep 5
done

利用mysqldump命令备份MySQL数据库的脚本(带注释版,适合学习和测试使用)

#!/bin/bash
# MYSQLDBUSERNAME是MySQL数据库的用户名,可自定义
MYSQLDBUSERNAME=root
# MYSQLDBPASSWORD是MySQL数据库的密码,可自定义
MYSQLDBPASSWORD=password
# MYSQBASEDIR是MySQL数据库的安装目录,--prefix=$MYSQBASEDIR,可自定义
MYSQBASEDIR=/usr/local/mysql
# MYSQL是mysql命令的绝对路径,可自定义
MYSQL=$MYSQBASEDIR/bin/mysql
# MYSQLDUMP是mysqldump命令的绝对路径,可自定义
MYSQLDUMP=$MYSQBASEDIR/bin/mysqldump
# BACKDIR是数据库备份的存放地址,可以自定义修改成远程地址
BACKDIR=/var/backup/db
# 获取当前时间,格式为:年-月-日,用于生成以这种时间格式的目录名称
DATEFORMATTYPE1=$(date +%Y-%m-%d)
# 获取当前时间,格式为:年月日时分秒,用于生成以这种时间格式的文件名称
DATEFORMATTYPE2=$(date +%Y%m%d%H%M%S)
# 如果存在MYSQBASEDIR目录,则将MYSQDATADIR设置为$MYSQBASEDIR/data,具体是什么路径,就把data改成什么路径,否则将MYSQBASEDIR设定为/var/lib/mysql,可自定义
[ -d $MYSQBASEDIR ] && MYSQDATADIR=$MYSQBASEDIR/data || MYSQDATADIR=/var/lib/mysql
# 如果mysql命令存在并可执行,则继续,否则将MYSQL设定为mysql,默认路径下的mysql
[ -x $MYSQL ] || MYSQL=mysql
# 如果mysqldump命令存在并可执行,则继续,否则将MYSQLDUMP设定为mysqldump,默认路径下的mysqldump
[ -x $MYSQLDUMP ] || MYSQLDUMP=mysqldump
# 如果不存在备份目录则创建这个目录
[ -d ${BACKDIR} ] || mkdir -p ${BACKDIR}
[ -d ${BACKDIR}/${DATEFORMATTYPE1} ] || mkdir ${BACKDIR}/${DATEFORMATTYPE1}
# 获取MySQL中有哪些数据库,,根据mysqldatadir下的目录名字来确认,此处可以自定义,TODO
DBLIST=`ls -p $MYSQDATADIR | grep / |tr -d /`
# 从数据库列表中循环取出数据库名称,执行备份操作
for DBNAME in $DBLIST
    # mysqldump skip one table
    # -- Warning: Skipping the data of table mysql.event. Specify the --events option explicitly.
    # mysqldump --ignore-table=mysql.event
    #
    # --routines,备份存储过程和函数
    # --events,跳过mysql.event表
    # --triggers,备份触发器
    # --single-transaction,针对InnoDB,在单次事务中通过转储所有数据库表创建一个一致性的快照,此选项会导致自动锁表,因此不需要--lock-all-tables
    # --flush-logs,在dump转储前刷新日志
    # --ignore-table,忽略某个表,--ignore-table=database.table
    # --master-data=2 ,如果启用MySQL复制功能,则可以添加这个选项
    # 将dump出的sql语句用gzip压缩到一个以时间命名的文件
    do ${MYSQLDUMP} --user=${MYSQLDBUSERNAME} --password=${MYSQLDBPASSWORD} --routines --events --triggers --single-transaction --flush-logs --ignore-table=mysql.event --databases ${DBNAME} | gzip > ${BACKDIR}/${DATEFORMATTYPE1}/${DBNAME}-backup-${DATEFORMATTYPE2}.sql.gz
    # 检查执行结果,如果错误代码为0则输出成功,否则输出失败
    [ $? -eq 0 ] && echo "${DBNAME} has been backuped successful" || echo "${DBNAME} has been backuped failed"
    # 等待5s,可自定义
    /bin/sleep 5
done

执行效果:

[root@htvm ~]# ./backupmysqlbydate.sh
mysql has been backuped successful
test has been backuped successful
[root@htvm ~]# ls /var/backup/db/2015-07-27/
mysql-backup-20150727195515.sql.gz  test-backup-20150727195515.sql.gz
[root@htvm ~]#

标签:mysqldump,备份MySQL数据库,MySQL数据库备份,mysql备份,mysql备份脚本

--end--

使用mysqldump进行MariaDB 的备份 

使用mysqldump导出数据库 

基于mysqldump快速搭建从库 

恢复mysqldump创建的备份集 

使用mysqldump命令行工具创建逻辑备份 

本文永久更新链接地址

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
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.