所以以我的最后一个问题为基础这里我让它工作了,但后来我尝试用它制作一个 crontab,每 2 分钟检查给定日期的行数。
所以我的脚本看起来像这样
1 test=/root/test
2 n="$(cat /root/test)"
3 t="$(date)"
4 echo "there were $n lines in $test at $t" >> rtest1
每当我运行脚本时,rtest1 都会向我显示所需的结果:
there were 224 lines in /root/test at Fri Aug 10 10:28:25 EEST 2018
there were 224 lines in /root/test at Fri Aug 10 10:28:25 EEST 2018
there were 224 lines in /root/test at Fri Aug 10 10:28:26 EEST 2018
there were 224 lines in /root/test at Fri Aug 10 10:28:26 EEST 2018
there were 224 lines in /root/test at Fri Aug 10 10:28:26 EEST 2018
there were 224 lines in /root/test at Fri Aug 10 10:28:26 EEST 2018
然而,当由于 crontab 发生这种情况时,出于某种奇怪的原因,有时它会省略行号,如下所示:
there were 229 lines in /root/test at Fri Aug 10 10:20:51 EEST 2018
there were lines in /root/test at Fri Aug 10 10:22:01 EEST 2018
there were 224 lines in /root/test at Fri Aug 10 10:24:01 EEST 2018
there were 224 lines in /root/test at Fri Aug 10 10:26:02 EEST 2018
there were lines in /root/test at Fri Aug 10 10:28:01 EEST 2018
这就是我的 crontab 的样子:
[root@centos7desk ~]# crontab -l
* * * * * ps axu | wc -l > /root/test
*/2 * * * * /root/script.sh
我不知道为什么会发生这种情况。
答案1
基本上,如果两个 crontab 条目同时执行,这就是一个竞争条件。在“无值”情况下,输出文件已创建但尚未填充(因为ps axu | wc -l
运行时间可能比脚本更长)。
为了克服这个问题,您可以sleep 5
在脚本的开头添加 a (从技术上讲,这不会阻止竞争条件,但除非您的系统负载很重,否则它不太可能发生)。或者将所有内容放入一个脚本中(这可能是更好的解决方案)。