[Linux] Backup + Upload - Google Drive
Create a directory:
The directory can be inside the server folder.
Suggested name: backup_DB
Creating a database backup:
Create a .sh file in the server folder
#!/bin/bash
path="/PATH TO THE FOLDER WHERE THE BACKUP WILL BE CREATED/" # Path where the backup of your database
nameBackup="SQL FILE NAME" # Environment where it is hosted
mysqlUser="MYSQL LOGIN" # Your MySQL user
mysqlPass="MYSQL PASSWORD" # Your MySQL password
mysqlDatabase="DATABASE NAME" # The name of your database
TIMER="$(date +'%d-%m-%Y-%H-%M')"
if [[ -z "$mysqlUser" || -z "$mysqlPass" || -z "$mysqlDatabase" ]]; then
echo "Please fill in username, password and database in settings."
else
# Create the backup
mysqldump -u$mysqlUser -p$mysqlPass $mysqlDatabase > $path"/"$nameBackup"-"$TIMER".sql"
# Change to the backup directory
cd $path
# Remove older backups if there are more than 10 files
backups=($(ls -t $nameBackup-*.sql))
if (( ${#backups[@]} > 10 )); then
for file in "${backups[@]:10}"; do
rm "$file"
done
fi
echo "Backup Complete."
fi
Create a cron job on Linux to run the .sh file on a scheduled basis:
The suggestion is to have two times to generate 2 .sql files, the first at 6:10 after the default servesave, and the other at 23:10 after the server is busy.
Adding cron to Linux Cron will execute the backup .sh file automatically.
Open the cron list:
crontab -e
Cron:
10 6,23 * * * /path/for/your/script.sh
Remember: change the machine's time to your local time, for example:
sudo timedatectl set-timezone America/Sao_Paulo
This will ensure that cron runs the .sh files at the correct time.
Permission for the .sh file:
After saving the .sh file with the code, add the permission so it can be executed:
chmod +x backup.sh
Credits: Leotk.
Last updated