Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect OS type using Perl

I want to use Perl to detect the OS type.

For example:

Let's say I have an installer, in order to know which commands the installer needs to run. I'll have to detect what operating system is installed, for example Linux. Let's say it's Linux. Now which type of Linux?

  • Fedora
  • Ubuntu
  • CentOS
  • Debian
  • etc.

How would I do this?

like image 475
StackedFlow Avatar asked Dec 05 '22 12:12

StackedFlow


2 Answers

The first step is to check the output of the $^O variable.

If the output is for example

linux

you need more processing to detect which distribution is used.

See perldoc perlvar.

So far, you can run lsb_release -a to see which distribution is used.

If this command is not present, you can test the presence of files like:

/etc/debian_version # debian or debian based
/etc/redhat-release # rpm like distro

Other files tests examples: Detecting Underlying Linux Distro


Consider xaxes' solution too using the Linux::Distribution module to check the distribution.


If you want to detect the package manager, you can try this approach:

 if ($^O eq "linux") {
     my $pm;

     do{
         if (-x qx(type -p $_ | tr -d "\n")) {
             $pm = $_;
             last;
         }
     } for qw/apt-get aptitude yum emerge pacman urpmi zypper/;

     print $pm;
 }
like image 147
Gilles Quenot Avatar answered Dec 07 '22 00:12

Gilles Quenot


According to perlvar, either $OSNAME or $^O will give you the operating system. This is also equivalent to using $Config{'osname'} (see Config for more). A special note for Windows systems:

In Windows platforms, $^O is not very helpful: since it is always MSWin32 , it doesn't tell the difference between 95/98/ME/NT/2000/XP/CE/.NET. Use Win32::GetOSName() or Win32::GetOSVersion() (see Win32 and perlport) to distinguish between the variants.

In order to get the exact platform for a Linux box, you'll need to use a module like xaxes mentioned in his answer.

like image 31
Jonah Bishop Avatar answered Dec 07 '22 00:12

Jonah Bishop