Skip to content

Instantly share code, notes, and snippets.

@unxmaal
Forked from anonymous/backup.sh
Last active December 3, 2016 18:10
Show Gist options
  • Save unxmaal/d65fd64e20e4b61ff532dc7aa2e5b407 to your computer and use it in GitHub Desktop.
Save unxmaal/d65fd64e20e4b61ff532dc7aa2e5b407 to your computer and use it in GitHub Desktop.
A backup script for daily file and database backups for a single website
#!/bin/bash
### Globals
# Set the date
date=$(date +"%d-%b-%Y")
# Set default file permissions
umask 117
# Site name
# site_name="sitename.com"
#
# Database credentials
# user="db_user"
# password="super_secret_pass"
# host="localhost"
# db_name="db_name"
# Files source
# files_src_dir="/path/to/$site_name/"
# Backup path
# backup_path="/path/to/backups/"
# Get env vars from an external file, so you’re not hard-coding them
# inside the script.
. ./.backup_options
# You could also read -s the password — but that’s still not secure.
# Real security is hard. ;)
# Put things in functions. Functions are good, and will make your
# life easier later.
main(){
# Set today's backup path
today_backup_path="$backup_path$site_name-$date"
# Create today's backup directory
# >> we use -p just in case we have to re-run the script
# >> also, let's case these statements, so the script will
# fail if these entries fail.
if ! mkdir -p "$today_backup_path" ; then
echo "ERROR: failed to create $today_backup_path"
return 1
fi
# Dump database into SQL file
if ! mysqldump --user="$user" --password="$password" --host="$host" "$db_name" > "$today_backup_path/$db_name-$date.sql" ; then
echo "ERROR: mysqldump failed!"
return 1
fi
# Copy the srouce directory files to today's backup path
if ! cp -a "$files_src_dir." "$today_backup_path" ; then
echo "ERROR: copy failed!"
return 1
fi
# TAR the archive
if ! tar -zcf "$today_backup_path.tar.gz" "$today_backup_path" ; then
echo "ERROR: archiving failed!"
return 1
fi
# Now remove the directory that we used to create the archive
# >> Here's a super dangerous mistake. If $today_backup_path is null, or set to say, your
# homedir, you can accidentally and automatically nuke many things.
# First ensure today_backup_path isn't empty
if [[ -n "$today_backup_path" ]] ; then
# Then ensure it's a directory
if [[ -d "$today_backup_path" ]] ; then
if ! rm -rf "$today_backup_path" ; then
echo "ERROR: failed to rm today's backup!"
return 1
fi
else
echo "ERROR: today_backup_path is not a directory!"
return 1
fi
else
echo "ERROR: today_backup_path is null!"
return 1
fi
# Delete files older than 15 days
if [[ -n "$backup_path" ]] ; then
find $backup_path/* -mtime +15 -exec rm {} \;
else
echo "ERROR: missing backup_path"
return 1
fi
}
main
exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment