I was given the task to write a script that makes daily backups of our company's MySQL databases and keeps only the most recent <n> of them (where <n> is a positive integer

). This is not a big deal for anyone with some knowledge of shell scripting, but I publish it nonetheless, because I think the implementation is quite nice and might spare some minutes/hours for beginners.
The script uses zsh (the shell of my choice), but most of it would work in Bash, too. You should run it from crontab on a daily basis, which means you have to:
- place the attached mysql_backup.zsh in a directory of your choice (eg. ${HOME}/bin)
- open the script in a text editor (eg. vi) and add the necessary "do_backup" commands with the necessary parameters for backing up your databases
- extract your current crontab with something like
crontab -l > .crontab
- add a new line to the end of ".crontab" with this:
0 3 * * * ${HOME}/bin/mysql_backup.zsh
- overwrite the crontab settings with
crontab .crontab
That's all.
Comments
MySQL backup v1.3.0
MySQL backup v1.4.0
-ctimeparameter offinddid not contain the+prefix before the number of days, thus it was only deleting backups that were exactly of the specified age and skipped older ones.MySQL backup v1.5.0
nice(with "-n +19") to limit the CPU resources consumed by the bzip2 compressionmysqldumpcommand from the bzip2 compression so the former is not affected in any way by the latterMySQL backup v1.6.0
hostnameparameter for ado_backupcall is "localhost" or "127.0.0.1", then the generated filename will contain the real hostname (fetched from the output of thehostnamecommand) instead