一键脚本备份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
BACK_TIME=$(date +%Y%m%d%h%s)
DATA_NAME=$1
USER=$2
PASS=$3
HOST=$4 if [ -z $HOST ] then HOST="localhost" fi params=$#
FILENAME="database_${DATA_NAME}_backup_${BACK_TIME}.sql" if [[ $params == 3 $params == 4 ]] then echo "Start backup DB:${DATA_NAME} " 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 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 做定时备份就好了