Assuming the container-stopping command "blocks" (i.e., exits after the container has been stopped), you can probably run the container-starting command with a systemd user service instead of directly from a shell. Suppose you need to start multiple containers, you can write a service template to $HOME/.config/systemd/user/
. The filename of a service template should have @
before .service
(e.g. [email protected]
).
Here's an example for you:
[Unit]
PartOf=%i.scope
After=%i.scope
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/systemd-run --user --scope -u %i sh -c 'sleep 1d &'
ExecStop=/usr/bin/sleep 1m
As you can see, the scope name needs to be "known" instead of a generated one.
With the template, you can now start the container with e.g. systemctl --user start test@container-a
. You should now see the corresponding scope remain until its "agent" service has stopped (i.e., the ExecStop=
command has exited).
You might need to run systemctl --user daemon-reload
whenever you have made changes in the service (template) file(s).
P.S. Obviously if you need to pass extra container-specific arguments (that are not the same string as the scope name) to the container-starting/stopping command, you probably have to write multiple service files instead of using a template.