我想创建一个Shell脚本,它在我做备份程序之前每天都作为cronjob运行。
此shell脚本应删除文件夹中的文件 但不要删除:
如何扩展此代码:
find /path/to/files* -type f -mtime +180 -delete
答案 0 :(得分:0)
<强>计划强>
- 将文件详细信息(名称和日期)读取到数组
- 循环数组检查日期的业务条件
- 如果业务逻辑未设置标志
,则删除该文件
<强> cleanup_files.sh 强>
#!/bin/bash
# replace with your path to files..
list_files=$(ls ./ -lt --time-style=+"%Y-%m-%d" |
awk '{ if( $1 != "total" )printf $7","$6"\n"; }' |
tr '\n' ' ');
four_weeks_ago=$(date -d "now - 4 weeks" +%s);
seven_days_ago=$(date -d "now - 1 weeks" +%s);
six_months_ago=$(date -d "now - 6 months" +%s);
for fil in $list_files
do
filename=$(printf "$fil\n" | cut -d, -f1);
fdate=$(printf "$fil\n" | cut -d, -f2);
flag=0;
ts=$(date -d "$fdate" +%s);
wday=$(date -d "$fdate" +%u);
mday=$(date -d "$fdate" +%d);
# check if created in last seven days..
if [ "$ts" -ge "$seven_days_ago" ]; then
flag=1;
fi
# check if created on a sunday in last four weeks
if [ "$wday" -eq "7" ] && [ "$ts" -ge "$four_weeks_ago" ]; then
flag=1;
fi
# check if file created on first of month for last 6 months
if [ "$mday" -eq "01" ] && [ "$ts" -ge "$six_months_ago" ]; then
flag=1;
fi
# if flag is not set delete file
if [ "$flag" -ne "1" ]; then
printf "deleting $filename..\n";
# uncomment only after proper testing..
# rm "$filename";
fi
# printf "$fil\n";
done;