Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a systemd unit is active in a bash script

I'm writing a script to automatically install a bind server on a CentOs 7 distribution.

I'm stuck with systemctl status, because it does not produce an error code (it's right, since a status is not an error) I can use.

What I want is to check whether the service is started (active). What is the best and efficient way to do this?

like image 325
math Avatar asked May 05 '15 14:05

math


People also ask

How do I know if systemd is running?

To check a service's status, use the systemctl status service-name command. I like systemd's status because of the detail given. For example, in the above listing, you see the full path to the unit file, the status, the start command, and the latest status changes.

How do I check if a service is running in bash?

Bash commands to check running process: pgrep command – Looks through the currently running bash processes on Linux and lists the process IDs (PID) on screen. pidof command – Find the process ID of a running program on Linux or Unix-like system.

Is test a bash command?

On Unix-like operating systems, test is a builtin command of the Bash shell that tests file attributes, and perform string and arithmetic comparisons.


1 Answers

The best way to check if a service is active is with the systemctl is-active command:

# systemctl start sshd
# systemctl is-active sshd >/dev/null 2>&1 && echo YES || echo NO
YES
# systemctl stop sshd
# systemctl is-active sshd >/dev/null 2>&1 && echo YES || echo NO
NO
like image 193
larsks Avatar answered Sep 18 '22 05:09

larsks