Skip to the page

Linux for operators · mid

systemd units, cron and safe shell scripts

Services and scheduled jobs fail in quiet ways: wrong unit type, a minimal cron environment, and shell scripts that delete the wrong thing when a variable is empty.

The notes

What you must know

  • Type=forking waits for the started process to fork and exit. A program that stays in the foreground, such as java -jar, needs Type=simple or exec (or notify if it supports sd_notify).
  • Use absolute paths in ExecStart. Add After= and Wants= network-online.target when the service needs the network at boot. Run as a dedicated user, not root.
  • start request repeated too quickly comes from the start rate limit after repeated failures. Read journalctl -u <unit> for the real error. Use Restart=on-failure with a delay.
  • cron runs with a minimal PATH, no login profile, another working directory and /bin/sh. By default it mails output to a local mailbox nobody reads, so redirect output to a log.
  • In a crontab line % means newline and must be escaped. cron uses the system time zone, so on a UTC server write the UTC time you want.
  • A script needs set -euo pipefail, quoted variables, checked arguments (${1:?usage}) and a checked cd before any rm. An empty variable in rm -rf can delete the wrong directory.
  • Do not parse ls output. Use find with -print0 or -delete and test on a copy first.
  • A log cleanup script: lock with flock, compress only rotated files, delete old compressed files with find -mtime, check disk with df, and alert if it is still over the threshold.

The red pen

Common traps: mistake → fix

  • Mistake: A script that works by hand works in cron

    Fix: cron has a different environment.

  • Mistake: If cd fails the script stops

    Fix: without set -e it carries on in the wrong directory.

  • Mistake: Restart=always fixes a failing unit

    Fix: it hides the error and hits the rate limit.

Easy to hard

Questions interviewers ask, easy to hard

  1. Our systemd unit fails with start request repeated too quickly. What is wrong?
  2. The backup script works by hand but not from cron. What do you check?
  3. Would you let this cleanup script run in production?
  4. Write a script to compress old logs, delete older ones and alert on disk use.

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview