0

Currently an active service(telegraf) is running on a machine. Want to automate few steps in which the initial is to check the service is running from a shell script.

I am running systemctl status telegraf command to check the status of the service manually. and the output is,

telegraf.service - The plugin-driven server agent for reporting metrics into InfluxDB
   Loaded: loaded (/usr/lib/systemd/system/telegraf.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2021-05-19 12:26:17 UTC; 3 weeks 5 days ago
     Docs: https://github.com/influxdata/telegraf
 Main PID: 1297 (telegraf)
    Tasks: 9 (limit: 49778)
   Memory: 106.3M
   CGroup: /system.slice/telegraf.service
           └─1297 /usr/bin/telegraf -config /etc/telegraf/telegraf.conf -config-directory /etc/telegraf/telegraf.d

I want to capture the value active (running) in my script, how to do it in Shell script?

enter image description here

1 Answers1

4

you could parse the output of the systemctl status command.

But the easier way to get information on whether a service is running is by using the is-active sub command of systemctl. For example:

user@host:~$ systemctl is-active postfix
active

If the service is not active the returned string is inactive.

So in your script you can either check the string that is returned (active or inactive) or you can check the return code of the above mentioned command. If the service is active the command returns with 0 otherwise it'll retrun with non-zero return code.

Greetings :)