A Simple linux shell

目录结构是: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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值