1

I cannot receive the crontab output report by email as an attachment. I tried the following code, but I receive a blank file:

50 * * * * root touch /home/text_created >> 
/home/log_crontab.txt | mail -s "Email Subject" -a "/home/log_contab.txt" 
this_is_my_email

It is a really simple test just to run crontab along with its email sending feature. What's the matter with the code above?

1
  • You can't split a crontab command over multiple lines like that.
    – Barmar
    Feb 21, 2018 at 21:54

2 Answers 2

2

You received a blank file because the /home/log_contab.txt file was empty when the mail was sent.

Why:

Processes on the both sides of the anonymous pipe (|) start simultaneously; so, when the command on the left hand side appends STDOUT (assuming any) to the /home/log_contab.txt file, the mail command has finished executing (with a blank /home/log_contab.txt file as attachment as presumably it was empty to start with).

To get what you want, run one after another, conditionally:

50 * * * * command_1 && command_2

Change the commands accordingly.

0

Piping the output to mail is not right. You're redirecting the output to a file, so nothing will be sent to the pipe. And when you use a pipe, the two commands are run concurrently, so mail doesn't wait for the first command to finish.

Run them sequentially with ;.

And touch doesn't produce any output. If you want a message logging that the cron job succeeded, you need to write that explicitly.

50 * * * * root if touch /home/text_created; then echo "Touch successful"; else echo "Touch failed"; fi >> /home/log_crontab.txt 2>&1; mail -s "Email Subject" -a "/home/log_contab.txt" this_is_my_email
8
  • Sorry, but it is not working. I just tried this code: */2 0 * * * root touch /home/file_created_at_`date +\%H:\%M`.txt > /home/log.txt ; mail -s "subject" -a "/home/log.txt" my_email. It outputs again a blank file. Feb 21, 2018 at 23:44
  • @R99Photography AFAIK the touch command doesn't write anything to standard output - what exactly are you expecting to see in the attached file? Feb 22, 2018 at 0:00
  • touch is only an example of a task I expect to run. Let's imagine another task like "copy a directory from one location to another one for backyp", I expect to send an email with the log that the crojob was succesfully run. Feb 22, 2018 at 9:17
  • Copying a file doesn't produce any output, either.
    – Barmar
    Feb 22, 2018 at 18:41
  • I've updated the answer to show how you can log a message reporting the success of the operation.
    – Barmar
    Feb 22, 2018 at 18:43

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.