需求如下:
需要将3个月内的文件留在/app/tmp下,便于查询。
3个月以上的两种文件,按照创建的日期,移动到另外一个目录,比如/app/tmp/2011/03表示2011年3月份的所有文件。
最后这个脚本放在crontab里面,每天都执行。就是每天都会移一些文件到/app/tmp/nnnn/nn里面去,保证/app/tmp下永远是最近的3个月内的文件。
(这里脚本里改成了/app/test,防止测试前直接用于环境)
可能会有bug,写的逻辑也不是最精妙的,不过也算学到了一点ksh的特点。对于ksh中的算数运算和自定义函数都有了最简单的例子。
- #!/bin/ksh
- function month_to_num {
- typeset month=$1
- case $month in
- "Jan") print 1;;
- "Feb") print 2;;
- "Mar") print 3;;
- "Apr") print 4;;
- "May") print 5;;
- "Jun") print 6;;
- "Jul") print 7;;
- "Aug") print 8;;
- "Sep") print 9;;
- "Oct") print 10;;
- "Nov") print 11;;
- "Dec") print 12;;
- esac
- }
- file_dir="/app/test"
- flag=0
- oldest_file_name=`ls -lt $file_dir| grep -E "txt|xml" | tail -1 | awk '{print $9}'`
- oldest_file_month_tmp=$(istat $file_dir/$oldest_file_name | grep modified | awk '{print $4}')
- oldest_file_month="`month_to_num "$oldest_file_month_tmp"`"
- oldest_file_day=`istat $file_dir/$oldest_file_name | grep modified | awk '{print $5}'`
- oldest_file_year=`istat $file_dir/$oldest_file_name | grep modified | awk '{print $NF}'`
- now_month=`date +\%m`
- now_day=`date +\%d`
- now_year=`date +\%Y`
- (( duration= (( now_year - oldest_file_year )) * 12 + now_month - oldest_file_month ))
- echo $duration
- while [[ $flag -ge 0 ]]
- do
- flag=-1
- while [[ $duration -gt 3 || $duration -eq 3 && $now_day -eq $oldest_file_day ]]
- do
- flag=0
- if [ -d $file_dir/$oldest_file_year/$oldest_file_month/ ]
- then
- mv $file_dir/$oldest_file_name $file_dir/$oldest_file_year/$oldest_file_month/
- else
- mkdir -p $file_dir/$oldest_file_year/$oldest_file_month
- mv $file_dir/$oldest_file_name $file_dir/$oldest_file_year/$oldest_file_month/
- fi
- oldest_file_name=`ls -lt $file_dir| grep -E "txt|xml" | tail -1 | awk '{print $9}'`
- oldest_file_month_tmp=$(istat $file_dir/$oldest_file_name | grep modified | awk '{print $4}')
- oldest_file_month="`month_to_num "$oldest_file_month_tmp"`"
- oldest_file_day=`istat $file_dir/$oldest_file_name | grep modified | awk '{print $5}'`
- oldest_file_year=`istat $file_dir/$oldest_file_name | grep modified | awk '{print $NF}'`
- (( duration= (( now_year-oldest_file_year )) * 12 + now_month - oldest_file_month ))
- done
- done
做如下总结:
1.ksh的算数运算应该是比较有特点的。
2.$()和反逗点"`"应该是差不多的作用。
3.最简单的自定义函数的写法和调用。
小学生水平的脚本……请大家指教