Bash

用於在伺服器上備份每個數據庫但省略系統數據庫的腳本

  • April 16, 2019

我已經閱讀了很多關於這個主題的文章,但我沒有找到適合我需要的文章。所以,基本上我想為 MySQL 伺服器上的每個數據庫做兩個備份:一個在中午(12 PM)和另一個在午夜(12 AM),但我想省略系統數據庫:mysqlinformation_schema(據我所知有沒有其他的請告訴我)。在閱讀了很多主題後,我使用了這個 bash 腳本:

#!/bin/sh
now="$(date +'%d_%m_%Y_%H_%M_%S')"
filename="db_backup_$now".gz
backupfolder="/home/backups"
fullpathbackupfile="$backupfolder/$filename"
logfile="$backupfolder/"backup_log_"$(date +'%Y_%m')".txt
echo "mysqldump started at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
mysqldump --user=userbackup --password=***** --default-character-set=utf8 database | gzip > "$fullpathbackupfile"
echo "mysqldump finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
find "$backupfolder" -name db_backup_* -mtime +7 -exec rm {} \;
echo "old files deleted" >> "$logfile"
echo "operation finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
echo "*****************" >> "$logfile"
exit 0

該腳本對數據庫進行了備份database並保留了 7 個最後的.tar.gz文件。任何人都可以幫助我改進這個腳本,以便我可以備份系統數據庫以外的每個數據庫並為每個數據庫保留 7 個最後的副本?

我目前正在使用PostgreSQL,並且我做的事情看起來非常接近您想要實現的目標,所以這是我的備份腳本:

#!/bin/bash
#
#------------------------------------------------------------------------------
# Editable parameters:
#
## Filesystem Location to place backups.
BACKUP_DIR="/path/to/backup/folder"
## The user used to connect to postgres instance
USER="postgres"
PWD="pwd_in_plaintext_is_not_a_"
## Just the date string that will be appended to the backup files name
BACKUP_DATE="$(date +'%d_%m_%Y_%H_%M_%S')"
## Numbers of days you want to keep copie of your databases
NUMBER_OF_DAYS=7
## Uncomment following line if you want to overwrite the whole folder each time
#rm -rf ${BACKUP_DIR}/backupFulldb-*
#
#------------------------------------------------------------------------------
# don't change anything below this line

# Vacumm al databases before begin to backup
vacuumdb --all -U ${USER}

DATABASES=`psql -U ${USER} -l -t | cut -d'|' -f1 | sed -e 's/ //g' -e '/^$/d'`
for i in ${DATABASES}; do
 if [ "$i" != "template0" ] && [ "$i" != "template1" ]; then
   echo Dumping $i to ${BACKUP_DIR}
   pg_dump -U ${USER} --column-inserts $i | gzip -c >  ${BACKUP_DIR}/backupFulldb-$i-${BACKUP_DATE}.out.gz
 fi
done
find ${BACKUP_DIR} -type f -prune -mtime +${NUMBER_OF_DAYS} -exec rm -f {} \;

您只需要一個列出 mysql 實例中所有數據庫的查詢,並將其替換為DATABASES數組。閱讀這篇文章這篇文章,我想你可以。執行以下操作:

while read line
do 
   DATABASES+=("$line")
done < <(mysql -u${USER} -p${PWD} INFORMATION_SCHEMA -e "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA")

當然,修復您要排除的 dbs 名稱:

if [ "$i" != "mysql" ] && [ "$i" != "information_schema" ]; then

引用自:https://unix.stackexchange.com/questions/245425