Home Blog CV Projects Patterns Notes Book Colophon Search

Redirecting Standard Output to Supress Messages in Cron Jobs

2 Jun, 2007

Under Linux if you want to suppress messages written to the standard output stream you can redirect them to a special file called /dev/null which discards all data written to it (but reports that the write operation succeeded), and provides no data to any process that reads from it (it returns EOF).

This functionality is really useful when specifying commands for cron scripts if you only want to be notified if errors occur because you can redirect standard output to /dev/null so that only messages to standard error will be reported.

Let's demonstrate this. Create a file named output_test.py with the following content:

#!/usr/bin/env python

import sys
sys.stdout.write("From stdout\n")
sys.stderr.write("From stderr\n")

Run this command to change the permissions so the file can be executed:

chmod 755 output_test.py

Then you can test it:

james@bose:~$ ./output_test.py
From stdout
From stderr

As you can see the output from both standard output and standard error are displayed. Now let's try redirecting to /dev/null:

james@bose:~$ ./output_test.py > /dev/null
From stderr

As you can see only standard error is actually displayed. We can make use of this in the example below where some_script.py is run every 4 hours and any error information is emailed to james@example.com but any standard output is ignored:

0 */4 * * * some_script.py > /dev/null

With this example an email will only be sent if information is written to standard error.

You might also want to redirect error output to /dev/null instead (but this would normally not be recommended - error messages are there for a reason). The way to do this depends on your shell. I'm using Bash so I can do so like this:

james@bose:~$ ./output_test.py 2> /dev/null
From stdout

In this example the 2 just before > says that the standard error should be redirected to /dev/null. A 1 would refer to standard output and a 0 would refer to standard input. You can also redirect both:

james@bose:~$ ./output_test.py 1> /dev/null 2> /dev/null

Learn more about redirection at the wikipedia page.

Copyright James Gardner 1996-2020 All Rights Reserved. Admin.