Skip to content

Instantly share code, notes, and snippets.

@wangye
Created March 5, 2012 04:53
Show Gist options
  • Save wangye/1976681 to your computer and use it in GitHub Desktop.
Save wangye/1976681 to your computer and use it in GitHub Desktop.
Bash shell for backup WordPress and MySQL database
#!/bin/bash
# Author: wangye
# For more information please visit:
# http://wangye.org/
# 请在使用本脚本前做好测试工作,脚本功能仅供参考,
# 对于可能的潜在问题造成损失,本人不承担责任。
MYSQL_USERNAME="mysql-username"
MYSQL_PASSWORD="mysql-password"
# 下面这行指示接收备份文件的电子邮件地址
BACKUP_RECEVIER="[email protected]"
BACKUP_FILENAME="/var/sample-site" # 需要备份的目录
BACKUP_DBNAME="sample" # 需要备份的数据库名称
BACKUP_PREFIX="backup_" # 备份文件的前缀
# 下面一些命令路径可以通过whereis获取
MYSQLDUMP_PATH="/usr/bin" # mysqldump 命令所在的路径
TARCOMPRESSOR_PATH="/bin" # tar 命令所在的路径
RM_PATH="/bin" # rm 命令所在的路径
MUTTMAIL_PATH="/usr/bin" # mutt 命令所在的路径
TEMP_PATH="/tmp" # 临时目录
# 产生临时名称形如 backup_20120221 名称
make_backup_name() {
TEMPNAME=${BACKUP_PREFIX}$(date +"%Y%m%d")
}
# 产生临时备份目录
make_backup_dir() {
make_backup_name
TEMPDIR=${TEMP_PATH}/$?
mkdir -m 777 -p $TEMPDIR
}
backup_files() {
${TARCOMPRESSOR_PATH}/tar -zcvf \
${TEMP_PATH}/${TEMPNAME}.tar.gz ${BACKUP_FILENAME}
}
backup_databases() {
local EXPORTDIR=$1
${MYSQLDUMP_PATH}/mysqldump -u${MYSQL_USERNAME} \
-p${MYSQL_PASSWORD} \
${BACKUP_DBNAME} >${EXPORTDIR}/${BACKUP_DBNAME}.sql
${TARCOMPRESSOR_PATH}/tar -zcvf \
${TEMP_PATH}/${TEMPNAME}_${BACKUP_DBNAME}.tar.gz ${EXPORTDIR}
}
send_byemail() {
echo "**IMPORTANT BACKUP** Hi! :-)\n\n$(uname -a)"| \
$MUTTMAIL_PATH/mutt -s "** System Backup$(date +%Y-%m-%d)" \
-a ${TEMP_PATH}/${TEMPNAME}_${BACKUP_DBNAME}.tar.gz \
${TEMP_PATH}/${TEMPNAME}.tar.gz -- \
${BACKUP_RECEVIER}
}
# 清除产生的临时文件(使用了rm -rf怕怕中,不过目标路径正确就OK啦)
cleanup() {
$RM_PATH/rm -rf $TEMPDIR
$RM_PATH/rm -rf ${TEMP_PATH}/${TEMPNAME}_${BACKUP_DBNAME}.tar.gz
$RM_PATH/rm -rf ${TEMP_PATH}/${TEMPNAME}.tar.gz
}
main() {
make_backup_dir
backup_databases $TEMPDIR
backup_files
send_byemail
cleanup
}
main
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment