Skip to content

Instantly share code, notes, and snippets.

@vaibhavpandeyvpz
Last active June 18, 2023 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vaibhavpandeyvpz/400d31eef6b7f66f477beefe159545cf to your computer and use it in GitHub Desktop.
Save vaibhavpandeyvpz/400d31eef6b7f66f477beefe159545cf to your computer and use it in GitHub Desktop.
Shell script to backup MySQL/MariaDB database to Dropbox.

mybak.sh

Install dbxcli and place it inside bin folder in your home directory.

# mark binary as executable
$ chmod a+x ~/bin/dbxcli

# login to your account
$ ~/bin/dbxcli account

Create a backup folder in your home directory.

$ mkdir ~/backup

Save your MySQL/MariaDB credentials in a file named .my.cnf in your home directory:

$ nano ~/.my.cnf

Put contents similar to below, make sure to replace values:

[mysqldump]
user=root
password=root_password

Download and place the mybak.sh file into bin folder in your home directory then issue below command.

$ chmod a+x ~/bin/mybak.sh

Now set up a cron job to schedule backup for database of your choice.

$ crontab -e

Insert below line to the end of cron configuration:

0 10 * * * env DB_NAME=test PATH="$PATH:$HOME/bin" ~/bin/mybak.sh >> /dev/null 2>&1
#!/bin/bash
localBackupDir=${LOCAL_BACKUP_DIR:-$HOME/backup}
remoteBackupDir=${REMOTE_BACKUP_DIR:-backups}
dbHost=${DB_HOST:-localhost}
dbPort=${DB_PORT:-3306}
echo "Changing to '$localBackupDir'..."
cd "$localBackupDir"
echo "Dumping database..."
mysqldump -h $dbHost -P $dbPort $DB_NAME | gzip > $DB_NAME.sql.gz
echo "Uploading to Dropbox..."
dbxcli put "$localBackupDir/$DB_NAME.sql.gz" "$remoteBackupDir/$(date '+%F_%H-%M-%S').sql.gz"
echo "Cleaning up..."
rm -f $DB_NAME.sql.gz
echo Done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment