Skip to content

Instantly share code, notes, and snippets.

@yock
Created March 22, 2017 14:59
Show Gist options
  • Save yock/efb0d1a1db3386be632b7505337470ba to your computer and use it in GitHub Desktop.
Save yock/efb0d1a1db3386be632b7505337470ba to your computer and use it in GitHub Desktop.
Super primitive database backup script
#!/bin/bash
backup_date=$(date +%s)
defaults_file=./my.cnf
destination=./backups
basename=backup
cleanup=false
cleanup_interval="+30"
dryrun=false
compress=false
verbose=false
declare -a databases
while getopts "b:c:d:i:n:sxjv" opt; do
case $opt in
b) destination=$OPTARG;;
c) defaults_file=$OPTARG;;
d) databases+=("$OPTARG");;
i) cleanup_interval=$OPTARG;;
n) basename=$OPTARG;;
s) dryrun=true;;
x) cleanup=true;;
j) compress=true;;
v) verbose=true;;
esac
done
log() {
if [ "$verbose" = true ]; then
echo $1
fi
}
backup_file_path="$destination/$basename-$backup_date.sql"
backup_command="mysqldump --defaults-file=$defaults_file --databases ${databases[*]} > $backup_file_path"
compress_command="bzip2 $backup_file_path"
outdated_backups_command="find $destination -daystart -maxdepth 1 -mtime $cleanup_interval -print"
if [ "$dryrun" = true ]; then
echo $backup_command
if [ "$compress" = true ]; then
echo $compress_command
fi
if [ "$cleanup" = true ]; then
echo "These files would be deleted:"
$outdated_backups_command
fi
else
log "Creating backup file..."
eval $backup_command
if [ "$compress" = true ]; then
log "Compressing backup file..."
eval $compress_command
fi
if [ "$cleanup" = true ]; then
log "Cleaning up old backups..."
eval $outdated_backups_command | xargs -r -d "\n" rm
fi
log "Done."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment