#!/bin/bash#输入参数:文件名filename=$1#源文件目录directory=/opt/docker/cloud-driver-training/apps#备份文件目录backupdir=$directory/backup#删除备份文件函数(备份文件数量设有有上限,超过上限会删除更早之前的备份文件)function deleteFiles() { if [ -z $filename ]; then echo "==========>param filename is null" return fi #列出所有同名文件,按文件更新时间倒序排序 files=`ls -t $backupdir | grep "$filename"` index=1 #保留的最大备份文件数量 maxFileCount=3 for file in $files do #当前备份文件数量大于最大备份文件数量,则删除历史的备份文件 if [ $index -gt $maxFileCount ]; then echo "==========>backup files count > $maxFileCount, delete history file $backupdir/$file" rm -rf $backupdir/$file fi index=$[$index+1] done echo "==========>fileCount:$index"}#文件备份函数function backup() { #源文件 sourceFile=$directory/$filename #如果源文件存在,执行备份 if [ -f $sourceFile ]; then backupFile=$backupdir/$filename`stat -c %y $sourceFile | cut -c 1-10` echo "==========> moving $sourceFile to $backupFile" mv $sourceFile $backupFile #备份完后,清除历史备份文件(如果超出最大备份数) deleteFiles else echo "==========> $sourceFile is not found" fi}echo "==========> do backup"backupecho "==========> backup finish"