Parsable output from systemctl (for example list all units)

Solution 1:

I use this for machine-parsable output, adding --plain --no-legend, for example:

systemctl list-units -t service --full --all --plain --no-legend

Solution 2:

you can get json (or json-pretty) output by setting the --output flag:

systemctl list-units \
  --type service \
  --full \
  --all \
  --output json \
  --no-pager

if your version of systemctl is without json output support, you can get json like so:

systemctl list-units \
  --type service \
  --full \
  --all \
  --plain \
  --no-legend \
  --no-pager \
  | sed 's/ \{1,\}/,/g' \
  | jq \
    --raw-input \
    --slurp \
    'split("\n") | map(split(",")) | .[0:-1] | map( { "unit": .[0], "load": .[1], "active": .[2], "sub": .[3] } )'