我们平时都是在linux服务器上工作,有时候工作要处理很大的文件(源码,数据文件,exe),而服务器只给我很小的home空间,我就只能把文件放到/tmp目录下。然而服务器管理员会用脚本定时清理那些长时间没有访问的文件(大概一两天左右),身边经常有同事这一周好不容易弄来一堆文件,休息一个周末回来就发现已经没有了,于是鄙人写了个脚本用来自动刷新文件夹下所有文件时间戳的脚本
使用方法: nohup keepAlive 1.5& #运行keepAlive,在未来的1.5天内刷新文件夹下所有文件的时间戳
基本原理就是靠touch命令刷新文件时间戳,脚本真正蛋疼之处是靠shell计算浮点数,由于shell自带的计算只能精确到整数,只能靠awk来帮忙了……
文件:keepAlive
- #!/bin/sh
- #Usage : run script under certain directory, to keep files under this directory fresh
- #Example: nohup keepAlive 1.5&
- #Note: directory should have permission to write files under current directory
- #Visit given directory recursively and use touch command to update the timestamp of all files in it
- function freshDir() {
- for file in `ls $1`
- do
- touch $1"/"$file
- if [ -d $1"/"$file ]
- then
- freshDir $1"/"$file
- fi
- done
- }
- #Show help when script started without arguments
- function showHelp() {
- echo "Run script under certain directory, to keep files under this directory up to date and not be deleted"
- echo "Example: nohup ~yantang/tools/keepAlive 1.5&"
- echo "Then all files under current directory will be refreshed in the next 1.5 days "
- echo "Kill it manually when you no longer need it"
- }
- if [ $# -gt 0 ]
- then
- daysAlive=$1
- else
- showHelp
- exit
- fi
- curDate=`date`
- echo "The time now: $curDate"
- echo "The directory will be alive for $daysAlive days"
- startTime=`date +%s`
- currentTime=$startTime
- typeset days=$(echo ${currentTime} ${startTime}|awk '{print ($1-$2)/86400 }')
- isAlive=1
- while [ $isAlive -gt 0 ]
- do
- freshDir "."
- sleep 600 #Sleep 10 minutes
- currentTime=`date +%s`
- days=$(echo ${currentTime} ${startTime} | awk '{print ($1-$2)/86400 }')
- isAlive=$(echo ${days} ${daysAlive}|awk '{if($1<$2) print 1; else print 0;}')
- done
- curDate=`date`
- echo "Now the time is $curDate .keepAlive stopped running. Bye"
转载于:https://blog.51cto.com/donald/1101095