2015-12-19 43 views
1

我正在编写一个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} 
+0

你可以使用'LS -t'了点。 – sjsam

+0

什么? – Naveen

+0

它对输出进行排序,最新的文件列在第一位。查看我的答案。我已经在脚本里面解释了一些事情。 – sjsam

回答

0

我想你可以使用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 Parameter Expansion

+0

我将文件放在同一个文件夹中并运行脚本。它给错误。 ls:无法访问mysql_metadata_backup_Sat:没有这样的文件或目录 – Naveen

+0

'FILE = mysql_metadata_backup _ $(date'+%Y-%m-%d_%H-%M-%S').sql'不正确,我猜。你可以做'temp = $(date'+%Y-%m-%d_%H-%M-%S')&& FILE = mysql_backup_ $ temp.sql' – sjsam

+0

真棒Sjsam,它与你最后的答案一起工作。非常感谢 – Naveen