Skip to content

Instantly share code, notes, and snippets.

@kendrickjr
Created January 11, 2023 19:48
Show Gist options
  • Save kendrickjr/34d4f7925f3e3de612aa8155a6d70c1b to your computer and use it in GitHub Desktop.
Save kendrickjr/34d4f7925f3e3de612aa8155a6d70c1b to your computer and use it in GitHub Desktop.
MySql Backup in linux

Here's an example of a simple bash script that can be used to backup a MySQL database:

#!/bin/bash

# Set the backup directory and file name
BACKUP_DIR="/path/to/backup/dir"
DATE=$(date +"%Y-%m-%d")
BACKUP_FILE="database-$DATE.sql"

# Set the MySQL credentials
MYSQL_USER="username"
MYSQL_PASSWORD="password"
MYSQL_HOST="localhost"
MYSQL_DB="database_name"

# Create the backup
mysqldump -u $MYSQL_USER -h $MYSQL_HOST -p$MYSQL_PASSWORD $MYSQL_DB > $BACKUP_DIR/$BACKUP_FILE

This script uses the mysqldump command to create a backup of the specified MySQL database. The backup is saved in the BACKUP_DIR directory with a file name in the format "database-YYYY-MM-DD.sql". You can adjust mysqldump command options as per your requirements You will need to replace the placeholders for the MySQL credentials with your actual values, and also configure the correct path for the backup directory.

You can schedule this script to run automatically using the cron job.

crontab -e

Then add the below line to schedule the backup everyday at 12AM

0 0 * * * /path/to/script/backup.sh

It's also recommended to encrypt your backup file before storing it in a different location, to protect your data in case of a security breach.

crontab -e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment