brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: systemd-run --wait reports runtime and exit code when a command ends

Systemd
~/tips/tip-systemd-run-wait-runtime-report

sudo systemd-run --wait -P -G -p CPUAccounting=yes -p MemoryAccounting=yes /usr/local/bin/backup.sh

Runs a command as a service and prints its runtime and exit status afterwards.

I like knowing how long a job ran and how it ended without wrapping it in time and checking $? by hand. systemd-run gives you both when you ask it to wait.

By default systemd-run starts your command as a background service and returns right away. With --wait it stays until the service has stopped and then prints a short report: the total runtime and the exit code and status of the main process. Add -P (--pipe) to see the command’s own output in your terminal as well.

sudo systemd-run --wait -P -G -p CPUAccounting=yes -p MemoryAccounting=yes /usr/local/bin/backup.sh

The two -p properties switch on cgroup accounting for this one run. The manual says CPU, memory, IO and IP figures only appear in the report when the matching accounting is on, so with them you also get the CPU time the job consumed and its memory use. -G (--collect) unloads the unit afterwards even when it failed, so a failed test run doesn’t stay behind in systemctl --failed.

The exit code of systemd-run is the exit code of your command, so it works in a script too:

sudo systemd-run --wait -q /usr/local/bin/backup.sh || echo "backup failed"

-q hides the report when you only care about success or failure.

One caveat: --wait can’t be combined with --scope or with the timer options, so this is for a command you run now. And because it runs as a real service, it starts in a clean environment without your shell’s variables. That is exactly why I’d reach for it before turning a script into a unit: what you measure here is how it behaves under systemd.

Further reading: systemd-run(1) manual page, systemd.resource-control(5) manual page

More Systemd tips [Service] sudo mkdir -p /etc/systemd/system/service.d [Service] printf 'hunter2' | sudo systemd-creds encrypt --name=dbpass – dbpass.cred systemd-analyze timespan 1h30min All Systemd tips (88) All topics

Link