应开发需求,有些锁文件生成之后不会在固定时间内删除,造成程序的计划任务会卡死,于是需要一个检查对比locks文件的脚本来实时检测这个目录下的*.locks文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/bash
while true
do
#获取当前时间
curren_time=\`date +%H:%M:%S\`

#--time-stype=FORMAT
ls -l --time-style=+%H:%M:%S /xxxxxx/*.locks >/tmp/locks 2>/dev/null
while read -r line
do
#文件内容
file_time=\`echo $line | awk -F ' ' '{print $6}'\`
#文件绝对路径及名称
File=\`echo $line | awk -F ' ' '{print $7}'\`

#转换成Unix时间戳
date1=\`date -d "$curren_time" +%s\`
date2=\`date -d "$file_time" +%s\`

#当前时间减去文件生产时间的差值进行比较(shell 的运算用expr关键字)
DD=$(expr $date1 - $date2)
if \[ $DD -gt 120 \];then
echo "$curren_time --- Greater than 2 minutes, $File will be delete."
sleep 2
rm -rf $File
fi
done < /tmp/locks
done

chmod +x /home/shell/check\_locks\_file.sh
nohup /bin/bash /home/shell/check\_locks\_file.sh >/var/log/check_locks.log &

两个关键点
1、ls命令的用法 : –time-type=FORMAT 参数
2、将常规的时间转换成Unix时间戳