Linux Labs

Bash: text processing and scripts / Stage 8 of 9

A script on a schedule: environment, log, lock

Not running Starting usually ~20 s
Leave the lesson

Step 3 of 6 · theory · 5 min

The script's log

Everything the script prints inside a service goes to the journal — it shows what happened overnight.

The lines the script writes to the output stream and the error stream are put by systemd into the service's journal, marked backup.sh[process number] — sudo journalctl -u lab-backup showed them. So a script for a timer needs no log file of its own: it is enough to print what it did — saved archive/… — and report errors to stream 2.

After the script's lines, systemd writes the outcome: Main process exited, code=exited, status=2/INVALIDARGUMENT and Failed with result 'exit-code'. That is the script's exit status: set -e stopped the script at tar, tar's status became the script's status, and the service went into the failed state. systemctl status and monitoring will see the failure.

Run by hand, the script writes to the terminal. To get a line into the journal then as well, there is logger -t backup "text": an entry tagged backup, found with journalctl -t backup.

Check yourself 1 question

The set -euo pipefail line was removed from backup.sh, and the service ran from /, as at the start of the lesson. What will systemctl status lab-backup show after the run?

  • Without set -e, the script kept going: mv failed as well, and the last command to run was echo "saved …" with status 0. That is what systemd recorded.

  • The script waits for nothing: tar and mv reported their errors at once, and the script ended after the three-second sleep.

The script's status came from its last command, echo — zero — so systemd recorded a successful run. The journal meanwhile holds both the tar and mv errors and a saved … line about an archive that does not exist.

Key points

  • A script's output and errors inside a service go to the journal: sudo journalctl -u <service>.
  • The script's exit status decides whether the service run succeeded or failed.
  • logger -t tag "text" writes to the journal from any run, and journalctl -t tag finds the entry.
Ubuntu 24.04
Loading…