递归sqlmetadata备份的Shell脚本



我每天都在写一个shell脚本来自动备份sql元数据。我被夹在中间。我的方法是每天备份sql元数据,并删除旧备份,保留最后3次备份以确保安全。请帮助我执行删除以前的备份并保留最后3个备份的命令。

FILE= mysql_metadata_backup_$( date '+%Y-%m-%d_%H-%M-%S' ).sql
mysqldump -u userID --all-databases > ${FILE}

我想您可以使用bash参数扩展来实现您的目标。

将下面的bash脚本放在包含备份的文件夹中。

#!/bin/bash
file_list=($( ls -t mysql_metadata_backup*))
# The '-t' parameter of the 'ls' sorts the output according to modification time with newest displayed first.
rm $( echo ${file_list[@]:3})
# The ':3' does the magic slicing the array from the index 3
# All the files except the newest three are passed to the "rm" command.

运行它将删除除最新的三个备份之外的所有备份

也许您可以考虑添加一个cron作业来实现自动化。

参考:

Bash参数扩展

最新更新