18

I'm trying to run a script every minute (on a Docker container running Ubuntu 16.04).

The /etc/echo.sh simply echo the word "hi"

cat /etc/crontab
* * * * *  root /etc/echo.sh > /var/log/cron.log 2>&1


/etc/init.d/cron reload
 * Reloading configuration files for periodic command scheduler cron     [ OK ]

tail -f /var/log/cron.log
hi

After printing "hi" once, nothing happens anymore.

Any ideas why?

Kamil Maciorowski
  • 69,815
  • 22
  • 136
  • 202
Sig
  • 521
  • 1
  • 4
  • 13
  • 8
    Why are you outputting your script to /var/log/cron.log anyway? If you weren’t overwriting that file you would see the cron daemon log the execution of your script every minute in there instead. – Darren Feb 09 '19 at 07:22
  • 4
    Look at the cron.log's time stamp with `ls -l var/log/cron.log`. Notice anything? – Jens Feb 09 '19 at 11:34

2 Answers2

56

The script does run every minute but > truncates the file each time.

If the file does not exist, it shall be created; otherwise, it shall be truncated to be an empty file after being opened.

(source)

Use >> instead to append to the file. Even then sometimes it may be hard to tell if the file has just grown by one line. This is why it's good to use date instead of echo hi when testing something like this.

Kamil Maciorowski
  • 69,815
  • 22
  • 136
  • 202
  • Won't `tail` say `tail: cron.log: file truncated` if the file is truncated? Or am I misunderstanding how tail works – Ferrybig Feb 08 '19 at 20:27
  • 3
    @Ferrybig If `tail` notices the short moment between truncating and placing `hi` back, then it will. In my Kubuntu `echo hi > cron.log` triggers the message from `tail` in about half the cases. It's a race condition so your (and the OP's) mileage may vary. – Kamil Maciorowski Feb 08 '19 at 20:54
  • 23
    And this is why you always use `date` instead of `echo hi` when testing something like this. – marcelm Feb 09 '19 at 02:07
  • Alternatively include a timestamp, which can be seen to be updating. @marcelm Better include a parameter to make it dump the time, as the `date` implementation I just used only prints out the year, month, and day by default (and I wouldn't want to wait 24 hours to find out if it's working). – jpmc26 Feb 09 '19 at 05:20
  • 3
    @jpmc26 What `date` is that? The standard Unix `date` prints the date and time by default. – Barmar Feb 09 '19 at 06:52
  • 3
    @Barmar Actually, I've checked and apparently I was confused by the use of `-I`. Apologies. – jpmc26 Feb 09 '19 at 06:56
-1
*/1 * * * *  root /etc/echo.sh > /var/log/cron.log 2>&1

I think that this is the problem. You must change the crontab minute option to */1 to run that bash every minute.

Worthwelle
  • 4,538
  • 11
  • 21
  • 32
David
  • 1