1

So building on my last question here I got it to work, but then I tried making a crontab out of it, to check the number of lines at a given date every 2 minutes.

So my script looks like this

1 test=/root/test
2 n="$(cat /root/test)"
3 t="$(date)"
4 echo "there were $n lines in $test at $t" >> rtest1

And whenever I run the script, rtest1 shows me the desired result:

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

However, when it happens because of the crontab, for some bizzare reason, sometimes it omits the lines number like so:

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

This is how my crontab looks like:

[root@centos7desk ~]# crontab -l
* * * * * ps axu | wc -l > /root/test
*/2 * * * * /root/script.sh

I have no idea why this happens.

1

Basically this is a race condition if both crontab entries get executed at once. In the "no values" case the output file gets created but isn't filled yet (because ps axu | wc -l takes longer to run than your script probably).

To overcome you could add a sleep 5 at the beginning of the script (which, technically, doesn't prevent the race condition but makes it very unlikely to occur unless your system is under heavy load). Or put everything into one script (which probably is the better solution here).

|improve this answer|||||
  • Ah I see, thanks for the answer, I though they were executed in order :) But then, shouldn't test just retain it's former value just before it is overwritten? – iamAguest Aug 10 '18 at 7:43
  • 1
    @iamAguest No, all cron jobs scheduled for a particular time are executed concurrently. – Kusalananda Aug 10 '18 at 7:46
  • @iamAugust it gets overwritten immediately by the output redirection, it just remains empty too long – nohillside Aug 10 '18 at 10:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.