Shell Script Init Portability – How to Detect Init System Using the Shell?

initportabilityshell-script

This may have more to do with detecting operating systems, but I specifically need the init system currently in use on the system.

Fedora 15 and Ubuntu now use systemd, Ubuntu used to use Upstart (long time default until 15.04), while others use variations of System V.

I have an application that I am writing to be a cross-platform daemon. The init scripts are being dynamically generated based on parameters that can be passed in on configure.

What I'd like to do is only generate the script for the particular init system that they are using. This way the install script can be run reasonably without parameters as root and the daemon can be "installed" automagically.

This is what I've come up with:

  • Search for systemd, upstart, etc in /bin
  • Compare /proc/1/comm to the systemd, upstart, etc
  • Ask the user

What would be the best cross/platform way of doing this?

Kind of related, Can I depend on bash to be on the majority of *nix or is it distribution/OS dependent?

Target platforms:

  • Mac OS
  • Linux (all distributions)
  • BSD (all versions)
  • Solaris, Minix, and other *nix

Best Answer

For the second question, the answer is no and you should have a look at Resources for portable shell programming.

As for the first part - first of all, you certainly have to be careful. I'd say perform several tests to make sure - because the fact that someone does have systemd (for ex.) installed, does not mean it is actually used as the default init. Also, looking at /proc/1/comm can be misleading, because some installations of various init programs can automatically make /sbin/init a symlink hardlink or even a renamed version of their main program.

Maybe the most useful thing could be to look at the init scripts type - because those are what you'll actually be creating, no matter what runs them.

As a side note, you might also have a look at OpenRC which aims to provide a structure of init scripts that is compatible with both Linux and BSD systems.