Redirect output of cronjobs

Sometimes, the output of cron jobs needs to be saved and should not be sent via email, as it’s the default.

To achieve this, extend your cron command:

* * * * * /usr/bin/php ~/priv/foo.php 2>&1 >~/logs/foo.log

This will redirect stderr to stdout and redirect the output to ~/logs/foo.log. The file will be truncated on each run, so only the output of the latest execution is preserved.

To write each cron run to its own log file, we use date:

* * * * * /usr/bin/php ~/priv/foo.php 2>&1 >~/logs/foo_$(date +\%s).log

This will create a file suffixed with the unix timestamp of the execution, allowing to easily find the log file in question for a given execution.

The percentage sign needs to be escaped with a backslash, as cron treats percentage signs a comments, thus the cron command would be incomplete and will never run!