Skip to content
shellhacks.dev
Cron and Scheduling

Send cron output to a file

Send cron output to a log with >> file 2>&1. The order matters: 2>&1 before the file leaves stderr behind, and cron mails or drops it.

1 min read
Summarize in AI

A cron job writes to standard output and standard error, and you want both in one log file instead of in mail nobody reads.

Shell
cat > log.cron <<'EOF'
* * * * * (echo out; echo err >&2) >> /tmp/right.log 2>&1
* * * * * (echo out; echo err >&2) 2>&1 >> /tmp/wrong.log
EOF
crontab log.cron
sleep 65
echo "right.log:"; cat /tmp/right.log
echo "wrong.log:"; cat /tmp/wrong.log
Text
right.log:
out
err
wrong.log:
out

Redirections are applied left to right. In the first line >> file points standard output at the file, then 2>&1 points standard error at the same place. In the second line standard error is copied to where standard output is at that moment, which is still cron's pipe, and only then is standard output moved to the file, so err never reaches it. The behaviour is that of the shell, described in the redirection section of POSIX.

The log only grows. Rotate it with logrotate, or write a dated file name, and mind the percent sign rule when you do. Output that never reaches a file goes to the local mail spool when a mail program is installed, and is discarded otherwise.

Share

More snippets

Cron and Scheduling

Escape percent signs in a cron command

A percent sign in a crontab command ends the command and feeds the rest to stdin. Escape it with a backslash, or the date call below breaks at once.

1 min read
Cron and Scheduling

Set PATH in a crontab

Set PATH on a line at the top of a crontab, because cron runs jobs with a minimal PATH of /usr/bin and /bin and a tool in /usr/local/bin is not found.

1 min read
Cron and Scheduling

Set the shell for cron

Cron runs jobs with /bin/sh. Set SHELL=/bin/bash at the top of the crontab to use Bash features such as [[ ]], arrays and process substitution.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.