目录结构是:mydir下有同级的三个目录:archive log data
这个shell是在特定的时间运行的,主要的功能是将log目录下的文件移到archive目录下,文件名的要求是在原来的文件名加上时间戳(年月日,如20111122)。
另一个功能是删除data目录下21天前的文件,data目录下可能有多级目录,所以需要递归删除。
#!/bin/sh
# If the directory is not exist, create it first.
namefordir="/mydir/archive"
if [ ! -d $namefordir ]; then
mkdir $namefordir
fi
# Move file to archive directory and retain last modified time
cd log
# Find files that modified in one day
# find . -type f -mtime -1
FILE_DATE=`date +%Y%m%d`
for file in `ls`
do
# Get the last modified format time, like as: 201101100900.01
filetime=`ls --time-style=+%Y%m%d%H%M.%S -l "$file"|awk '{print $6}'`
# New file name
newfilename="$namefordir/$file.$FILE_DATE"
mv $file $newfilename
touch -m -t $filetime $newfilename
done
# Judge which file can be deleted, here remove the file older than 21 days
delFileByTime(){
echo "run delFileByTime() $1"
file_time=`stat -c%Y "$1"`
local_time=`date +%s`
n=$(( $local_time - $file_time ))
if [ "$n" -ge "1814400" ]; then
rm "$1"
echo "delete successful $1"
else
echo "The file < $1 > needn't to delete"
fi
}
# Process to recursively delete all files older than a given date
delFiles(){
echo "run delFiles()"
for dirfile in `ls "$1"`
do
if [ -d $1/$dirfile ]; then
echo "fun-this dir is $dirfile"
delFiles $1/$dirfile
else
echo "fun-this is a file $dirfile"
delFileByTime $1/$dirfile
fi
done
}
# Remove all data files older than 21 days from data directory
cd ../data
for deletefile in `ls`
do
if [ -d $deletefile ]; then
echo "main-this dir is $deletefile"
delFiles $deletefile
else
echo "main-this file is $deletefile"
delFileByTime $deletefile
fi
done