Wednesday, November 30, 2016

centos - When cron is completed How to get email notification and log in a file (both)




I am a Newbie to linux. I'm trying to figure out things. Can someone kindly help me how to combine these two commands?



(1) Normally cron can results can be directed to a log file by editing crontab in the below manner



*/10 * * * * /scripts/mysc.sh >> /home/ara/Desktop/test/log.txt 2>&1 


(2) and in case we need cron results to be emails we can use MAILTO=someemail@domain.com such as



MAILTO=someemail@domain.com

*/10 * * * * /scripts/mysc.sh


But how to combine both options (1) and (2)? I have seen some webhosting space do have both options enabled simultaneously. I did my research/googling but failed to do it. I'm using centos 6.5 and use crontab -e to edit.


Answer



Your first example sends both stderr and stdout to the file (2>&1) ; the MAILTO variable set in the cron will capture any output that is not redirected, and this combined with directing the output to the file means that no output is available for the cron to email.



I'd suggest using tee to append the output to the file as well as sending it to stdout; this answer - https://serverfault.com/a/472878/102867 - is very similar one to what you're asking to acheive.



Alternatively, follow the suggestion in the first answer, and write a wrapper script to more gracefully handle the output of the script, and you can then both log, and have the output of your script mailed



No comments:

Post a Comment

linux - How to SSH to ec2 instance in VPC private subnet via NAT server

I have created a VPC in aws with a public subnet and a private subnet. The private subnet does not have direct access to external network. S...