Sub topic 6
Capturing output and logs
This chapter assumes you can write basic shell scripts, know what stdout and stderr are, and have read the earlier chapters on cron syntax, cron's minimal environment, and systemd service and timer units. Here you will decide where a job's output goes, how to keep it readable, and how to stop log files from growing without limit.
Why output handling matters
A scheduled job has no terminal. Whatever it prints has to go somewhere, or it disappears. If you don't choose a destination, the scheduler chooses one for you, and the default differs between cron and systemd.
- Cron mails the output to the crontab owner, or to the address in
MAILTO. On many servers no mail system is installed, so the output is dropped without a trace. - systemd sends stdout and stderr of a service to the journal, where
journalctlcan read it.
The first rule is to decide on purpose. The second is to make sure a failure leaves evidence, which is the subject of the next chapter.
Streams and redirection in cron
Every process has two output streams. Stdout (file descriptor 1) carries normal output. Stderr (file descriptor 2) carries errors and diagnostics. A redirection sends a stream to a file instead of the default destination.
The example crontab from this tutorial ends with a redirection:
*/15 * * * * /usr/bin/flock -n /run/lock/sync.lock /usr/local/bin/sync.sh >> /var/log/sync.log 2>&1Read it from left to right:
>> /var/log/sync.logappends stdout to the file. A single>would truncate the file at every run and erase history.2>&1makes stderr go wherever stdout currently goes. Order matters.2>&1 >> filesends stderr to the old stdout (the mail pipe) and only stdout to the file.
The table shows common choices.
| Redirection | Effect | When to use it | Column |
|---|---|---|---|
| (none) | Output is mailed by cron | You have working local mail and want a message on any output | |
| `>> file 2>&1` | Both streams appended to one file | A simple log with interleaved messages | |
| `>> out.log 2>> err.log` | Streams in separate files | You want to scan errors quickly | |
| `> /dev/null` | Discards stdout, stderr still mailed | Noisy jobs where only errors matter | |
| `\ | logger -t tag` | Sends output to syslog | You want central logging without file management |
The last row deserves an example. Piping to logger hands each line to syslog, which on systemd machines lands in the journal:
*/15 * * * * /usr/local/bin/sync.sh 2>&1 | /usr/bin/logger -t syncYou can then read the output with journalctl -t sync. Note that a pipe changes which exit status the shell sees, a point we return to below.
Logging from inside the script
Redirection captures whatever the script prints. A script that prints nothing useful gives you a log that is empty or unreadable. Make the script describe what it does.
Three habits help:
- Prefix every line with a timestamp. Cron's redirected file has no timestamps of its own.
- Log the start, the end, and the outcome of each major step.
- Send diagnostics to stderr and results to stdout, so the two can be separated later.
#!/usr/bin/env bash
set -euo pipefail
log() {
printf '%s %s\n' "$(date -Is)" "$*"
}
err() {
log "ERROR: $*" >&2
}
trap 'err "failed at line $LINENO"' ERR
log "start"
rows=$(psql -Atc 'select count(*) from orders' mydb)
log "orders table has ${rows} rows"
log "done"date -Is prints an ISO 8601 timestamp with the numeric UTC offset, such as 2026-11-28T04:31:39+00:00. The offset removes ambiguity when clocks change, which matters in the time zone chapter. The ERR trap runs when a command fails under set -e, so the log records which line broke.
You can also route the whole script's output once, near the top, instead of redirecting in the crontab:
#!/usr/bin/env bash
set -euo pipefail
exec >> /var/log/report.log 2>&1
echo "$(date -Is) report starting"exec with only redirections changes the redirections of the current shell. Every later command inherits them. This keeps the crontab line short and puts the logging decision beside the code that depends on it.
Output under systemd
A systemd service needs no redirection. The journal captures stdout and stderr and attaches metadata: unit name, process ID, timestamp, and priority.
journalctl -u backup.service --since today
journalctl -u backup.service -n 50 --no-pager
journalctl -u backup.service -p err
journalctl -u backup.service -o short-iso --since "2026-11-27 00:00"
journalctl -u backup.service -fThese commands show, in order: today's output, the last 50 lines, only messages of priority err or worse, full ISO timestamps from a given time, and a live follow.
A service marked Type=oneshot that runs from a timer produces a new group of lines for each activation. To see only the latest run, use the invocation ID:
systemctl show -p InvocationID --value backup.service
journalctl _SYSTEMD_INVOCATION_ID=<id-from-above>Priorities from a script
By default, everything on stdout is logged at priority info and everything on stderr at info too. To give lines a real severity, prefix them with a syslog level in angle brackets and enable the prefix parsing, which is the default for the journal's stream capture:
echo "<3>backup failed: disk full" # err
echo "<6>backup finished" # infoThen journalctl -p err returns only the first line. This lets monitoring and humans filter by severity without parsing text.
Sending output to a file instead
If you need a plain file, for example for a tool that reads logs from disk, systemd can do it without a shell redirect:
[Service]
StandardOutput=append:/var/log/backup.log
StandardError=inheritThe append: form requires a reasonably recent systemd (version 240 or later). Check with systemctl --version. Once you send output to a file, it no longer goes to the journal, so pick one place unless you have a reason to duplicate.
Keeping logs from filling the disk
An appended log file grows with every run. A job that runs every 15 minutes and writes 2 KB per run adds about 190 MB a year. A job that prints debug output on a failure loop can fill a disk in hours. Two controls prevent this.
Rotating files with logrotate
logrotate renames, compresses and deletes old log files on a schedule. Put a file in /etc/logrotate.d/:
# /etc/logrotate.d/sync
/var/log/sync.log {
weekly
rotate 8
compress
missingok
notifempty
copytruncate
}rotate 8keeps eight old files and deletes older ones.missingokandnotifemptyavoid errors and empty archives.copytruncatecopies the file and then empties the original. This suits cron jobs that open the log with>>each run. It can lose lines written during the copy. For jobs that run briefly and open the file fresh each time, plain rotation withoutcopytruncateis safe and loses nothing.
Test a configuration without changing files:
sudo logrotate -d /etc/logrotate.d/syncLimiting the journal
The journal enforces its own size limits. Set them in /etc/systemd/journald.conf:
[Journal]
SystemMaxUse=500M
MaxRetentionSec=1monthRestart systemd-journald after the change. Check current usage with journalctl --disk-usage.
The pipe problem
Piping a job's output to another command, as in sync.sh 2>&1 | logger -t sync, changes the exit status that the shell reports. By default a pipeline's status is that of the last command. If sync.sh fails but logger succeeds, the pipeline reports success.
In a script, set -o pipefail makes the pipeline fail if any stage fails. In a crontab line there is no such option, because cron runs the line with /bin/sh. Two fixes work:
- Put the pipe inside a script that sets
pipefail, then call that script from cron. - Use
exec >> file 2>&1or process substitution in the script instead of a pipe in the crontab.
This matters because the next chapter relies on the exit status to tell whether a run succeeded.
Common mistakes
- Using
>instead of>>. You see only the latest run, and a crash that produces no output leaves an empty file. - Writing
2>&1before the file redirect. Stderr then escapes the file. - Logging secrets. Do not print passwords, tokens or full connection strings. Logs are often readable by more users than the secret itself. Also avoid
set -xin jobs that handle credentials, because it prints every expanded command. - Relative paths in the log destination. Cron's working directory is the user's home, not where you tested. Use absolute paths.
- Unwritable log file. If the job's user cannot write
/var/log/sync.log, the shell fails before the script starts, and the script never runs. Create the file and set its owner in advance. - No timestamps. An untimestamped log cannot tell you whether the job ran last night.
Putting it together
The diagram shows the output paths for each scheduler and where rotation applies.
Choose one primary destination per job. For a new job on a systemd machine, the journal with a timer is the least work: no redirection, no rotation setup, and per-run filtering. For a cron job, append to a file with timestamps and add a logrotate rule at the same time you add the crontab line.
Exercises
Exercise
A crontab line reads 0 3 * * * /usr/local/bin/clean.sh 2>&1 >> /var/log/clean.log. The log stays empty, but cron mails error messages to the owner. What is wrong, and how do you fix it?
Show answer
The redirections are in the wrong order. 2>&1 runs first and points stderr at the current stdout, which is still the pipe to cron's mail. Only afterwards does >> /var/log/clean.log move stdout to the file. Error messages therefore go to mail. Reverse the order to >> /var/log/clean.log 2>&1 so both streams end up in the file.
Exercise
Your service report.service ran at 01:00 and again at 02:00. Write the command that shows only error-level messages from today, and name one setting that decides whether the output survives a reboot.
Show answer
journalctl -u report.service --since today -p err. Whether the journal survives a reboot depends on Storage= in /etc/systemd/journald.conf. With Storage=persistent, or an existing /var/log/journal directory under the default auto setting, logs are kept on disk. Otherwise they live in memory and are lost at reboot.