appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Logging and output

Lesson 3 of 58 minBeginner

Capture what a job prints so you can find out why it failed.

A scheduled job has no terminal. Whatever it prints is mailed to the user if the system has a mail setup, or silently lost. Decide where the output goes.

Redirect to a log file

0 * * * * /usr/local/bin/sync.sh >> /var/log/sync.log 2>&1
  • >> appends to the file. A single > would overwrite it each run.
  • 2>&1 sends error output (stream 2) to the same place as normal output (stream 1). Without it, errors are lost.
  • Put the redirection after the command.

Add a timestamp

Inside your script, print a line with the date at the start and at the end, and the exit code. Then the log tells you when each run happened and whether it succeeded.

#!/usr/bin/env bash
set -euo pipefail
echo "$(date -Is) start"
/usr/bin/rsync -a /data/ /backup/
echo "$(date -Is) done"

Noteset -euo pipefail stops the script at the first error, on unset variables and on failures inside pipes.

Or use the system logger

Pipe to logger -t myjob to send lines to syslog or the journal. Then journalctl -t myjob shows them with the same tools you use for the rest of the system.

CarefulLogs grow without limit. Add a logrotate rule or the disk will fill up one day.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What does 2>&1 do?
2. Which operator appends to a log file instead of overwriting it?
3. Why rotate logs?

Key terms