I want to list all services that starts with the letters lc-. Then I want to restart them.
How can I attchive this? I was thinking something like:
systemctl -l | grep ?? | systemctl restart ???
You can list the unit files with..
systemctl list-unit-files | grep -Eo '^lc-.*\.service'
-E
means you are going to use an extended regex expression.
-o
means you want only the matching parts.
'^lc-.*\.service'
is the regular expression to get only those services that start with 'lc-'.
Then to restart all of them you can use wildcards in your command
systemctl restart 'lc-*'
restart
is not limited to restarting already started/running units but will also start those which aren’t already started/running if they match that pattern.
-E
as you're not using any extended regex feature)
try-restart
which according to the man page only restarts already-running units
Commented
Jun 18 at 20:09
lc-*.service
, to restrict the targets to only services as asked in the question, is the best way to tackle this and makes jumping through hoops the way I did in my answer unnecessary: systemctl try-restart 'lc-*.service'
systemctl
can filter by unit type and unit state on its own, not to mention it can print the output as a JSON file, which allows extremely robust parsing, so you could print only running services as a JSON file:
systemctl --type=service --state=running --output=json
filtering out elements whose unit
key's value doesn't start with lc-
, printing just the unit's name:
jq -r '.[] | .unit | select(test("^lc-"))'
passing the output to xargs -r
+ sudo systemctl restart
(the -r
switch will prevent xargs
from running sudo systemctl restart
in case no running service matching the criteria was found; note that valid unit names can't include whitespace per systemd's specifications so piping the output to xargs -r
directly is safe):
xargs -r sudo systemctl restart
Putting everything toghether:
systemctl --type=service --state=running --output=json |
jq -r '.[] | .unit | select(test("^lc-"))' |
xargs -r sudo systemctl restart
sudo
and some of them are breaking parsing, just add a sudo
before the systemctl
command: systemctl --type=service --state=running --output=json | jq -r '.[] | .unit | select(test("^ls-"))' | xargs sudo systemctl restart
Too few arguments
" is because there were no results for the expression "^ls-"
... You needed "^lc-"
instead.
sudo
inside the jq
expression, so maybe there are services starting with lc-
and the jq
expression, broken as is, is breaking the pipe. On that note I have yet to figure out if they want to match lc-
or ls-
, they wrote two different things in the title and in the body of the question...