#!/bin/bash
$program="$0"
PIC_PATH=/home/liutao/test_delete
SHELF_LIFE=30
DELAY_LIFE=3
today=`date -d +%Y%m%d`
rename_suffix=_bak
delete_suffix=_del
function Log
{
local path="$PIC_PATH/pic_delete.log"
local now = `date +%Y%m%d %H:%M:%S`
echo "$program[$now] - $1" >> $path
}
// return seconds
function modify_time
{
local dir="$1"
local day=`stat "$dir" |grep Modify|sed 's/./ /g' |awk '{print $2,$3 }'`
local ret=`date -d "$day" +%s`
echo -n "$ret"
}
function delete_dir
{
Log "delete dir $1"
cd "$1"
rm -rf *
cd ..
rmdir "$1"
}
function MV
{
Log "mv $1 to $2"
mv -v "$1" "$2"
}
function can_rename
{
local dir="$1"
local now=`date +%s`
local mtime=`modify_time "$dir"`
if (( now - mtime > (SHELF_LIFE-1)*3600 )); then
echo -n "1"
else
echo -n "0"
fi
}
function can_delete
{
local dir="$1"
local now=`date +%s`
local mtime=`modify_time "$dir"`
if (( now - mtime > DELAY_LIFE*3600 )); then
echo -n "1"
else
echo -n "0"
fi
}
if [[ ! -d $PIC_PATH ]] ; then
Log "$PIC_PATH not exist"
exit 1;
else
cd $PIC_PATH
fi
i=0
count=0
while (( i < SHELF_LIFE )) ; do
dir=`date -d "-$i day" +%Y%m%d`
if [[ -d $dir ]] ; then
(( count++ ))
Log "$dir exists"
else
Log "$dir not exists"
break
fi
(( i++ ))
done
if (( count != SHELF_LIFE )) ; then
Log "only have $count dirs"
exit 0
fi
i=$SHELF_LIFE
j=0
to_rename=`date -d "-$i day" +%Y%m%d`
while [[ -d $to_rename ]] ;do
((j++))
Log "$to_rename exist"
can_rn=`can_rename "$to_rename"`
if [[ $can_rn == "1" ]]; then
MV "$to_rename" "$to_rename$rename_suffix"
else
Log "$to_rename modify recently"
fi
((i++))
to_rename=`date -d "-$i day" +%Y%m%d`
done
k=0
(( k=SHELF_LIFE+DELAY_LIFE ))
to_delete=`date -d "-$k day" +%Y%m%d`
if [[ $j -eq 1 ]]; then
if [ -d "$to_delete$rename_suffix" ]; then
MV "$to_delete$rename_suffix" "$to_delete$delete_suffix"
delete_dir "$to_delete$delete_suffix"
fi
# (( k++ ))
# to_delete=`date -d "-$k day" +%Y%m%d`
# while [ -d "$to_delete$delete_suffix" ]; do
# Log "$to_delete$delete_suffix exist"
# can_dl=`can_delete "$to_delete$delete_suffix"`
# if [[ $can_dl == "1" ]] ; then
# delete_dir "$to_delete$delete_suffix"
# fi
# done;
fi