fbpx

Shell Script to Take MySQL Backup

Here is an example of a shell script that can be used to back up a MySQL database:

				
					#!/bin/bash

# Set the MySQL user and password
MYSQL_USER="username"
MYSQL_PASSWORD="password"

# Set the name of the database to be backed up
DATABASE_NAME="database_name"

# Set the directory for the backup files
BACKUP_DIRECTORY="/path/to/backup/directory"

# Set the current date and time
NOW=$(date +"%Y-%m-%d-%H-%M-%S")

# Export the database to a SQL file
mysqldump -u $MYSQL_USER -p$MYSQL_PASSWORD $DATABASE_NAME > "$BACKUP_DIRECTORY/$DATABASE_NAME-$NOW.sql"

# Compress the SQL file using gzip
gzip "$BACKUP_DIRECTORY/$DATABASE_NAME-$NOW.sql"

				
			

This script uses the mysqldump utility to export the database to a SQL file, and then uses gzip to compress the file. The SQL file is named using the current date and time, so each backup will have a unique filename. You can customize the script by modifying the variables at the top to match your MySQL login details and the name of the database you want to back up.

To use the script, save it to a file with a .sh extension and make it executable using the chmod command:

				
					chmod +x [script_name.sh]

				
			

You can then run the script by typing its name and pressing Enter:

				
					./[script_name.sh]

				
			

It’s a good idea to schedule regular backups using a tool like cron so that you don’t have to remember to run the script manually. This will ensure that your MySQL databases are regularly backed up and protected against data loss.

Share:

Facebook
Twitter
Pinterest
LinkedIn

Social Media

Most Popular

Get The Latest Updates

Subscribe To Our Weekly Newsletter

No spam, notifications only about new products, updates.

Categories