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

A service's environment

A service runs the script in a different environment from your terminal — and the same path leads somewhere else inside it.

The path archive/partial.tar.gz, with no / at the start, is relative: it counts from the current directory. In the terminal, that is the directory you moved to with cd. systemd starts a service without logging in: the service gets neither the terminal's current directory nor what ~/.profile and ~/.bashrc set up — aliases and additions to PATH. systemd itself gives the service its environment.

You can look at it without touching lab-backup: systemd-run runs a command as a temporary service, --wait --pipe waits for it to finish and prints its lines in the terminal, and -p User=student runs it as you.

Exercise · look

Compare the terminal and a service

In ~/sched-lab, print the current directory and PATH first in the terminal, then in a temporary service run as student.

First, predict

Which directory will pwd print inside the temporary service?

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

The service starts in the root, and data for it means /data. Its PATH is short, four directories: a program from ~/bin or ~/.local/bin that you run by name in the terminal will not be found in a service.

This is fixed from one of two sides. In the unit: a WorkingDirectory=/home/student/sched-lab line in the [Service] section sets the current directory, and Environment=PATH=… sets PATH; after editing the file — sudo systemctl daemon-reload. In the script: absolute paths, or a cd to the right directory before the first command that needs it.

Ubuntu 24.04
Loading…