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 1 of 6 · on a machine · 5 min

Works by hand, fails as a service

What you will learn

  • Run a script as a systemd service with the right directory and find its output in the service's journal.
  • Explain how a service's environment differs from the terminal — the current directory and PATH.
  • Keep a second copy of a script from starting work with flock at the top of the script.

A colleague wrote ~/sched-lab/backup.sh — a backup of the data directory into the archive directory — and put it on the nightly lab-backup timer. By hand, the script works, yet in the morning there are no new archives. Run the backup by hand, then as the same service the timer starts, and read the service's journal.

Exercise · look

Run the backup by hand and as a service

In ~/sched-lab, run backup.sh by hand, then the same backup as the lab-backup service, and read the service's journal.

First, predict

By hand, the script saved an archive. What will sudo systemctl start lab-backup.service answer?

Now start the exercise, run the command and compare your prediction with the output.

Sign in and start The machine is available after signing in
Check yourself 1 question

By hand, backup.sh found data and archive, while inside the service tar says No such file or directory. Why?

  • The unit has User=student — check with systemctl cat lab-backup.service. And root would open student's directories without errors.

  • The script's first line, #!/bin/bash, picks bash inside the service too. tar started — those are its lines in the journal.

The data and archive/… paths are relative, and the service has a different current directory.

Ubuntu 24.04
Loading…