WishMeLz

生活其实很有趣

远程备份MySql数据库 shell

#!/bin/bash

# 设置变量
BACKUP_DIR="/app/backsql"  # 本地备份目录
MYSQL_USER=""  # MySQL 用户名
MYSQL_PASSWORD=""  # MySQL 密码
MYSQL_HOST="mysql..com"  # MySQL 服务器地址
MYSQL_PORT="3306"  # MySQL 端口号
DATABASE_NAME=""  # 要备份的数据库名称

BACKUP_FILE="$BACKUP_DIR/$DATABASE_NAME_$(date +\%Y-\%m-\%d).sql"
mkdir -p "$BACKUP_DIR"
mysqldump -h "$MYSQL_HOST" -P "$MYSQL_PORT" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD"  --set-gtid-purged=OFF "$DATABASE_NAME" > "$BACKUP_FILE"

if [ $? -eq 0 ]; then
    echo "Database backup successful: $BACKUP_FILE"
else
    echo "Database backup failed!" >&2
fi

find "$BACKUP_DIR" -type f -name "*.sql" -mtime +7 -exec rm {} \;