40

I've got a cron job that is set up like this in my crontab:

*/1 * * * *  sudo /home/pi/coup/sensor.py  >> /home/pi/sensorLog.txt

It puts stdout into sensorLog.txt, and any stderr it generates gets put into an email.

I want both stdout and stderr to go into sensorLog.txt, so I added 1>&2 to the crontab, which is supposed to make stderr go into the same place as stdout. It now looks like this:

*/1 * * * *  sudo /home/pi/coup/sensor.py  >> /home/pi/sensorLog.txt 1>&2

Now, both stdout and stderr both get put into an email, and nothing gets added to the file. This is the opposite of what I am trying to accomplish.

How do I get both stdout and stderr to get redirected to the file?

1 Answer 1

78

It's the other way around:

*/1 * * * *  sudo /home/pi/coup/sensor.py  >> /home/pi/sensorLog.txt 2>&1

2>&1 will redirect standard error (2) to standard output (1) which -in turn - was redirected to your log file. So, at the end, both stderr and stdout will go to your sensorLog.txt

Sign up to request clarification or add additional context in comments.

1 Comment

Very important note which should be on the first page of google search if someone asks if there are no logs for cron: 2>&1 should be after redirecting to file. ... 2>&1 >>$log doesn't work, use ... >>$log 2>&1 instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.