Writing backup Scripts

  • backupdb.shCreate a new file in the root directory.
db_user="root"
db_password="root"
db_name="demo"
backup_dir="/backup"
time="$(date +"%Y%m%d%H%M%S")"
mysqldump -u$db_user -p$db_password $db_name | gzip > $backup_dir/$db_name"_"$time.sql.gz
Copy the code

Run the following command to grant execution permission to the backupdb.sh file: chmod u+x backupdb.sh;

If you run the./backupdb.sh command directly, a warning is displayed:

mysqldump: [Warning] Using a password on the command line interface can be insecure.

To avoid warning messages, you can use the following configuration methods:

vi /etc/mysql/my.cnf

[mysqldump]
user=your_db_user_name
password=your_db_password 
Copy the code

After saving the configuration file, modify the backup script, which does not need to involve the user name and password.

db_name="demo"
backup_dir="/backup"
time="$(date +"%Y%m%d%H%M%S")"
mysqldump $db_name | gzip > $backup_dir/$db_name"_"$time.sql.gz
Copy the code

Run the script again, and there is no warning.

Creating a Scheduled Task

  • Rules for Cron expressions in Linux:
* * * * * * - - - - - - | | | | | | | | | | | + year [optional] | | | | +----- day of week (0 - 7) (Sunday=0 or 7) | | |  +---------- month (1 - 12) | | +--------------- day of month (1 - 31) | +-------------------- hour (0 - 23) +------------------------- min (0 - 59)Copy the code
  • Add the plan
Create a plan and execute it
crontab -e

# Enter the plan through VI or other editor, eg: Every Sunday at 0:00
0 0 * * 0 /backupdb.sh

# Check existing tasks
crontab -l
Copy the code

Note:

  • ifcrontab -lIf “no crontab for root – using an empty one” is displayed, the task creation fails.
  • By commandselect-editorSelect the editor.

If you have any questions or any bugs are found, please feel free to contact me.

Your comments and suggestions are welcome!

This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.