8

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 [email protected] such as

[email protected] */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.

2 Answers 2

10

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

4
  • I could achieve that by reading above answer and what i did was this /scripts/mysc.sh >> /home/ara/Desktop/test/log.txt 2>&1; mailx -s "Cron output" [email protected] < /home/ara/Desktop/test/log.txt thanks Andrew Commented Jul 6, 2014 at 14:33
  • 1
    @user3107413 That way you will always send the complete, ever increasing logfile via email. Do you want that? If not, better use tee. Commented Jul 6, 2014 at 15:46
  • hi Dubu.. Not sure what is the exact syntax.. Tried several times.. but failed .. not familiar with prod nor tee command syntax or functions.. thanks for helping .. Commented Jul 6, 2014 at 17:19
  • Finally this thing works perfect....... [email protected] */3 * * * * /scripts/mysc.sh 2>&1 | tee -a /home/ara/Desktop/test/log.txt Thanks Dubu Commented Jul 8, 2014 at 2:19
2

Cronjob for both log & email :

Run once a month at midnight of the first day of the month: 0 0 1 * *

0 0 1 * * /home/User/script.sh > /home/User/cronlog/`date +\%Y-\%m-\%d-\%H:\%M:\%S`-cron.log 2>&1 ; mailx -s "CronJob is run successfully" [email protected],[email protected] 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.