バックアップスクリプト

バックアップスクリプト

備忘録にサイトの自動バックアップスクリプト
仕様はローカルにファイルを保持せずAWSのS3にファイルをすべて転送し世代管理するもの。

#!/bin/bash
#set -ue
set -u
 
siteName='blog'
siteRoot='/home/blog/'
siteRootDir='public_html'
 
mysqlDB='blog'
mysqlUser='root'
mysqlPass='********'
 
s3BucketName='lalcs'
s3ConfigFile='/root/.s3cfg'
 
backupDir='/tmp/'
saveDate='30'
 
saveLocal='no'
 
#### ---------- Start Message ----------
echo 'Start Backup...'
 
#### ---------- Make Date ----------
nowDate=`date +%Y%m%d`
delDate=`date +%Y%m%d --date "${saveDate} days ago"`
 
#### ---------- S3 Check Upload ----------
s3cmd -c $s3ConfigFile ls s3://$s3BucketName/ | grep ${nowDate}_${siteName}.tar.gz > /dev/null 2>&1
flagUpload=$?
 
#### ---------- S3 Check Delete ----------
s3cmd -c $s3ConfigFile ls s3://$s3BucketName/ | grep ${delDate}_${siteName}.tar.gz > /dev/null 2>&1
flagDelete=$?
 
#### ---------- S3 Check ----------
if [ $flagUpload -eq 0 ]; then
    echo 'ERROR: Backup file exists.'
    echo 'FINISH!!'
    exit 1
fi
 
#### ---------- Move Dir ----------
cd $backupDir
 
#### ---------- Backup ----------
if [ ! -e "${nowDate}_${siteName}.tar.gz" ]; then
    #### Make Dir
    mkdir "${nowDate}_${siteName}"
    #### DB Dump
    mysqldump --user=$mysqlUser --password=$mysqlPass $mysqlDB | gzip > "${nowDate}_${siteName}/mysql_dump.gz"
    #### Site Backup
    tar zcf "${nowDate}_${siteName}/${siteRootDir}.tar.gz" -C $siteRoot $siteRootDir
    #### ALL gzip
    tar zcf "${nowDate}_${siteName}.tar.gz" "${nowDate}_${siteName}"
    #### Remove Dir
    rm -rf "${nowDate}_${siteName}"
 
    echo 'Backup Complete!'
fi
 
#---------- File Delete ----------
if [ -e "${delDate}_${siteName}.tar.gz" ]; then
    rm -f "${delDate}_${siteName}.tar.gz"
    echo 'File Delete Complete!'
fi
 
#### ---------- S3 Upload ----------
if [ $flagUpload -eq 1 ]; then
 
    #### ---------- Upload ----------
    s3cmd -c $s3ConfigFile put "${nowDate}_${siteName}.tar.gz" s3://$s3BucketName
 
else
    echo 'ERROR: File already exists in S3.'
fi
 
#### ---------- S3 Delete ----------
if [ $flagDelete -eq 0 ]; then
 
    #### ---------- Delete ----------
    s3cmd -c $s3ConfigFile del s3://$s3BucketName/"${delDate}_${siteName}.tar.gz"
 
else
    echo 'ERROR: There is no file is being deleted in S3.'
fi
 
#### ---------- Remove Local File ----------
if [ $saveLocal = 'no' ]; then
    rm -f "${nowDate}_${siteName}.tar.gz"
fi
 
echo 'FINISH!!'
exit 0

Cronで使ってみると起動しなかったので修正。

Profile

Kazuki Hayashi

I'm a full stack engineer.
I love programming and alcohol.

TOC