1

我是脚本新手。目前我有一个脚本,每天将目录备份到文件服务器。它会删除 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
4

2 回答 2

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
于 2013-07-29T19:21:18.283 回答
0

类似这样的东西可能会起作用:

ls -1t /path/to/directory/ | head -n 14 | tail -n 1

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

于 2013-07-29T16:32:21.120 回答