我正在编写一个shell脚本来每天自动执行sql元数据备份。我陷入了两者之间。我的做法是每天备份sql元数据,并删除旧备份以保持最后3个备份的安全。请使用该命令帮助我删除以前的备份,保留最后3次备份。用于递归sqlmetadata备份的shell脚本
FILE= mysql_metadata_backup_$(date '+%Y-%m-%d_%H-%M-%S').sql
mysqldump -u userID --all-databases > ${FILE}
我正在编写一个shell脚本来每天自动执行sql元数据备份。我陷入了两者之间。我的做法是每天备份sql元数据,并删除旧备份以保持最后3个备份的安全。请使用该命令帮助我删除以前的备份,保留最后3次备份。用于递归sqlmetadata备份的shell脚本
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作业来自动化这个。
参考:
你可以使用'LS -t'了点。 – sjsam
什么? – Naveen
它对输出进行排序,最新的文件列在第一位。查看我的答案。我已经在脚本里面解释了一些事情。 – sjsam