Systemd stop/disable all templated services that don't match a variable

Pete asked:

How can I programmatically stop/disable all templated systemd services which don’t match a specific variable. For example, I am running [email protected] and I want to stop/disable services which match [email protected]* except for [email protected].

This is the closest I’ve come, but list-units is output that is clearly not meant to be parsed by a machine, making it fragile:

export SERVICES="$(systemctl list-units [email protected]* --all | \
grep myservice | grep -v "@v1" | cut -f1 -d' ')"
if [ -n "$SERVICES" ]; then
/bin/systemctl stop $SERVICES
/bin/systemctl disable $SERVICES
fi

My answer:


Add --no-legend to the systemctl command to cut out some of the useless junk you don’t need. It will then list only the units, with no header or footer.


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.