Matej Petráš
Matej Petráš

Reputation: 67

Output stderr from cron to both file and email

I have Ubuntu server and I have one cron job that runs python script. I know I can get stderr output adding MAILTO= in crontab. I also know that standard way of outputting stdout and stderr to a file is by using 2>&1 redirection. Here comes my first problem.

Whatever I used I got error /bin/sh: 1: Syntax error: Bad fd number. After few hours I realized that it depends on sh version. The only one way I could output all to a file was using this command 00 00 * * * /usr/bin/python3 /data/script.py >& /data/logs/date +\%d_\%m_\%Y_out.log. I found on the internet that it belongs to csh or tcsh. I dont get it because I am using bash on my system. Why standard redirection like >>/log.txt 2>&1 didnt work for me?

My second problem is that I want to keep writing stdout and stderr to a file and want to keep emailing stderr via MAILTO. I was trying to play with tee command but without any succes. Thank you very much for your help

Upvotes: 2

Views: 1283

Answers (1)

amaksr
amaksr

Reputation: 7745

You can add variables to the beginning of your crontab file to ensure that proper shell is being used. For second problem you can use "tee" command, which will send everything from STDIN to STDOUT and also will save it to a file:

# crontab file example
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
[email protected]
0 * * * * /usr/bin/python3 /data/script.py 2>&1 | tee /var/log/log.txt

Upvotes: 1

Related Questions