systemctl
确实具有适合脚本编写的模式;使用show
而不是status
,并添加-p
/ --properties
和--value
选项以仅获取所需的输出。
这是一个示例(来自Ubuntu 17.04系统):
$ systemctl show -p SubState --value NetworkManager
running
运行(或其他方式)是SubState
。如果您想知道服务是否处于活动状态,请使用属性ActiveState
$ systemctl show -p ActiveState --value x11-common
inactive
$ systemctl show -p SubState --value x11-common
dead
来自的注释man
:
show [PATTERN...|JOB...]
Show properties of one or more units, jobs, or the manager
itself. If no argument is specified, properties of the
manager will be shown. If a unit name is specified, properties
of the unit are shown, and if a job ID is specified,
properties of the job are shown. By default, empty properties
are suppressed. Use --all to show those too. To select specific
properties to show, use --property=. This command is intended
to be used whenever computer-parsable output is required. Use
status if you are looking for formatted human-readable output.
-p, --property=
When showing unit/job/manager properties with the show command,
limit display to properties specified in the argument. The
argument should be a comma-separated list of property names,
such as "MainPID". Unless specified, all known properties are
shown. If specified more than once, all properties with the
specified names are shown. Shell completion is implemented for
property names.
--value
When printing properties with show, only print the value, and
skip the property name and "=".
inactive
或activating
两者兼而有之,systemctl status
并systemctl is-active
以3退出。(从systemd-241开始)解决方法:systemctl show service | grep -qx ActiveStatus=activating