#!/bin/bash
#rm_file>14day
ReservedNum=4 #保留文件数量
rm_file_dir='/home/sean/sean/rmfile' #需要删除文件的路径
cd $rm_file_dir #进入文件夹
RootDir=$(cd $(dirname $0); pwd) #当前文件路径
FileNum=$(ls -l | grep ^- | wc -l) #查找文件数量
OldFile=$(ls -rt *.dmp|head -1) #找出dmp最早文件
if [ $RootDir == $rm_file_dir ];then #判断所在目录是否正确
echo $RootDir
echo $rm_file_dir
while (($FileNum>$ReservedNum)) #文件数超过设置变量才执行
do
echo "Delete File:"$RootDir'/'$OldFile #打印要删除的文件名称
rm -f $RootDir'/'$OldFile #删除文件
let "FileNum--" #变量自减操作
OldFile=$(ls -rt *.dmp|head -1) #更新dmp最早文件
done
else
echo "error file path " #所在目录不对打印出路径错误
fi
转载自https://www.cnblogs.com/xiaomj/p/9232145.html
下面是自己改编的C语言版本:
#include "common.h"
int main()
{
//获取时间最早文件
char buf[4096] = {0};
FILE *pf = NULL;
if( (pf = popen("ls -rt *|head -1", "r")) == NULL )
{
return -1;
}
char strResult[4096];
fgets(strResult, sizeof(strResult), pf);
pclose(pf);
strResult[strlen(strResult)-1]='\0'; //delete the '\n'
printf( "the filename: %s\n",strResult);
//获取文件的大小
struct stat statbuf;
stat("/home/bekl/swapfile",&statbuf);
printf("the file size:%ld\n",statbuf.st_size);
//获取文件所属磁盘空间
memset(strResult,0,4096);
if( (pf = popen("df .", "r")) == NULL )
{
return -1;
}
fgets(strResult, sizeof(strResult), pf);
fgets(strResult, sizeof(strResult), pf);
strResult[strlen(strResult)-1]='\0';//delete the '\n'
printf("%s\n",strResult);
char fileSystem[20]="";
unsigned long int allSize = 0, usedSize = 0, availableSize = 0;
sscanf(strResult,"%s %ld %ld %ld",fileSystem,&allSize,&usedSize,&availableSize);
printf("fileSystem:%s,all:%ld,used:%ld,available:%ld\n",fileSystem,allSize,usedSize,availableSize);
pclose(pf);
}
用一句shell命令可以删除文件:
find ./log -name '*' -mtime +15 -exec rm {} >>/dev/null 2>/dev/null \\;
删除./log文件夹下超过15天的文件