一键脚本备份mysql数据库

经常需要备份数据库,写了个一键脚本,并且打包sql文件利用mysqldump,同时学习了下shell脚本。

脚本使用方法:

1.增加权限 chmod +x backup_database.sh 2.运行脚本 ./backup_database.sh db_name db_user db_pass  跟带参数一次是:数据库名称、账号、密码 host(可加可不加)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/bin/bash
#[email protected]
# ./bashup_database.sh db_name user pass host
#备份的数据库名称
BACK_TIME=$(date +%Y%m%d%h%s)
#database name
#获得参数名,即你需要备份的数据库名称
DATA_NAME=$1
#user
#获得参数名,即你需要备份的数据库账号名称
USER=$2
#pass
#获得参数名,即你需要备份的数据库密码
PASS=$3
#HOST,默认为localhost
HOST=$4
if [ -z $HOST ]
then
HOST="localhost"
fi
params=$#
#filename
FILENAME="database_${DATA_NAME}_backup_${BACK_TIME}.sql"
if [[ $params == 3 $params == 4 ]]
then
echo "Start backup DB:${DATA_NAME} "
#执行mysqldump备份数据库
if $(mysqldump -h ${HOST} -u${USER} -p${PASS} ${DATA_NAME} > "${FILENAME}");
then
echo " Dumped successfully!"
else
echo " Failed dumping this database!"
fi
#打包数据库
if $(gzip -c ${FILENAME} > "${FILENAME}.gz");
then
echo "gzip successfully!"
else
echo "gzip fail"
fi
#删除.sql文件
if $(rm -rf ${FILENAME});
then
echo "Completed backup"
fi

echo "Your DB:${DATA_NAME} backUp successfully Completed"
echo " "
else
echo "=============== ERROR ================"
echo "please run ./database_base.sh db_name user pass host"
echo "================ ERROR END============"
fi

最后配个linux下crontab -e 做定时备份就好了