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?
The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.
Understanding the concept of redirections and file descriptors is very important when working on the command line. To redirect stderr and stdout , use the 2>&1 or &> constructs.
It means that stderr ( 2 - containing error messages from the executed command or script) is redirected ( >& ) to stdout ( 1 - the output of the command) and that the latter is being redirected to /dev/null (the null device). This way you can suppress all messages that might be issued by the executed command.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With