Shell脚本:计算文件,删除'X'最旧的文件

时间:2013-07-29 16:25:25

标签: linux bash shell

我是脚本新手。目前我有一个脚本,每天将一个目录备份到文件服务器。它删除14天之外的最旧文件。我的问题是我需要它来计算实际文件并删除第14个最旧的文件。几天之后,如果文件服务器或主机停机几天或更长时间,备份时它将删除几天的备份甚至全部备份。等待时间。我希望它总是有14天的备份。

我尝试搜索并且只能找到与按日期删除相关的解决方案。就像我现在拥有的那样。

感谢您的帮助/建议!

我的代码,对不起它是我第一次尝试编写脚本:

#! /bin/sh

#Check for file. If not found, the connection to the file server is down!
if 
[ -f /backup/connection ];
then
echo "File Server is connected!"

#Directory to be backed up.
backup_source="/var/www/html/moin-1.9.7"
#Backup directory.
backup_destination="/backup"
#Current date to name files.
date=`date '+%m%d%y'`
#naming the file.
filename="$date.tgz"

echo "Backing up directory"

#Creating the back up of the backup_source directory and placing it into the backup_destination directory.
tar -cvpzf $backup_destination/$filename $backup_source
echo "Backup Finished!"

#Search for folders older than '+X' days and delete them.
find /backup -type f -ctime +13 -exec rm -rf {} \;

else
echo "File Server is NOT connected! Date:`date '+%m-%d-%y'` Time:`date '+%H:%M:%S'`" > /user/Desktop/error/`date '+%m-%d-%y'`
fi

2 个答案:

答案 0 :(得分:0)

像这样的东西可能有用:

ls -1t /path/to/directory/ | head -n 14 | tail -n 1
在ls命令中

,-1是仅列出文件名(没有别的),-t是按时间顺序列出它们(最新的第一个)。通过head命令管道只从ls命令的输出中获取前14个,然后tail -n 1仅从该列表中获取最后一个。这应该给出最新的第14个文件。

答案 1 :(得分:0)

这是另一个建议。以下脚本只是枚举备份。这简化了跟踪最后 n 备份的任务。如果您需要知道实际的创建日期,您只需检查文件元数据,例如使用stat

#!/bin/sh
set -e

backup_source='somedir'
backup_destination='backup'
retain=14
filename="backup-$retain.tgz"

check_fileserver() {
  nc -z -w 5 file.server.net 80 2>/dev/null || exit 1
}

backup_advance() {
  if [ -f "$backup_destination/$filename" ]; then
    echo "removing $filename"
    rm "$backup_destination/$filename"
  fi

  for i in $(seq $(($retain)) -1 2); do
    file_to="backup-$i.tgz"
    file_from="backup-$(($i - 1)).tgz"

    if [ -f "$backup_destination/$file_from" ]; then
      echo "moving $backup_destination/$file_from to $backup_destination/$file_to"
      mv "$backup_destination/$file_from" "$backup_destination/$file_to"
    fi
  done
}

do_backup() {
  tar czf "$backup_destination/backup-1.tgz" "$backup_source"
}

check_fileserver
backup_advance
do_backup

exit 0