1

I have a cronjob that calls a script. I want the output to be placed in a log file. The problem is that the log-file is created even if there is no output.

Since the job runs once an hour, and mostly has nothing to do. I am ending up with a lot of 0 byte files.

I could probably append to a single log file, but I wonder if there is a trick to use to prevent the log-file being created or to delete it if it is empty. (I don't really want to run a second cron-job to clean up after the first one)

A complication is the fact that the log filenames have a date/time appended to them. The line in crontab looks a bit like this:

/your/script.sh config.txt > outfilepath_`date +\%Y-\%m-\%d_\%H\%M`.html 

I guess that means I have to store the date in a variable first and then check if that file was created/empty. So if I take Stone's answer I end up with something like:

logfile=outfilepath_`date +\%Y-\%m-\%d_\%H`; your/script.sh config.txt > $logfile; if [! -s $logfile]; then rm $logfile; fi

but I don't know if that's possible inside crontab

Loopo
  • 415
  • 1
  • 9
  • 20

1 Answers1

2

You can write something like this:

/your/script > /your/log/file; if [ ! -s /your/log/file ]; then rm /your/log/file; fi
Stone
  • 7,011
  • 1
  • 21
  • 33
  • This is kind of what I want, but a bit like cleaning up after the mess has been made. There isn't a neat way to 'redirect-only-if-output'? (similar to the way an email is only sent if there is output). The process is complicated by the fact that the logfile name has a date appended (see edit) – Loopo Jul 31 '13 at 13:09