Linux – Convenient way to check if system is using systemd or sysvinit in BASH?

linuxscriptingsystemdsysvinit

I am defining common bash files which I want to use across different distributions. I need a way to check if system is using systemd or sysvinit (/etc/init.d/). I need this so I run appropriate command to start the service. What would be safe way to check for this? I currently check for existance of systemctl command, but is that really an option as there might be the case where systemctl command might be available, but it wouldn't necessarily mean that systemd is actually used?

Here is an excerpt from my current bash script:

#!/bin/sh
if [ command -v systemctl >/dev/null ]
then
    systemctl service start
else
    /etc/init.d/service start
fi

Best Answer

Systemd and init have pid = 1

pidof /sbin/init && echo "sysvinit" || echo "other"

Check for systemd

pidof systemd && echo "systemd" || echo "other"

enter image description here