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: systemctl is-active --quiet gives a script a plain yes or no

Shell
~/tips/tip-systemctl-is-active-quiet-script

if systemctl is-active --quiet docker.service; then

Returns exit code 0 when a unit is active, so shell scripts can test a service without parsing text.

Grepping the output of systemctl status to see whether a service runs breaks easily. There is a command made for scripts.

Use the exit code:

if systemctl is-active --quiet docker.service; then
  echo "docker is running"
else
  echo "docker is not running"
fi

The man page says is-active checks whether the specified units are active, meaning running, and returns exit code 0 if at least one is active, non-zero otherwise. Unless --quiet is given it also prints the current state to standard output. With the flag your script only sees the exit code.

Without --quiet you get a word such as active, inactive or failed, which suits a quick look at the terminal:

systemctl is-active docker.service

Watch the wording “at least one”. When you pass several units, a single active one makes the whole command succeed, so check units one at a time when all of them have to be up. The exit code also works in a chain, for example systemctl is-active --quiet docker.service && docker ps.

Active also says nothing about the next boot. Whether a unit starts at boot is a separate question, answered by systemctl is-enabled. A unit can be active now and disabled, or enabled and currently stopped, so a script that cares about both needs both checks.

Further reading: systemd: systemctl man page

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link