Perl OS type detection

I want to use Perl to determine the type of OS.

For instance:

Suppose I have an installer to find out what commands the installer needs to run, I will need to determine which operating system is installed, for example "linux". Say it's linux, now what type of linux?

  • Felt hat
  • ubuntu
  • CentOS
  • debain
  • and etc.

How can I do it?

+4
source share
4 answers

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

If the output is presented as an example

Linux

you need more processing to determine which distribution is being used.

See perldoc perlvar

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

If this command is not available, you can check for the presence of files such as:

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

Other sample file tests: http://www.novell.com/coolsolutions/feature/11251.html


Consider also the xaxes solution using the Linux::Distribution module to test the distribution.


If you want to discover 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; } 
+5
source

Alternatively, you can use Config (this is the main module), this is an example:

 use Config; print "$Config{osname}\n"; print "$Config{archname}\n"; 

On my Mac OS X, it prints:

 darwin darwin-2level 
+5
source

According to perlvar , either $OSNAME or $^O will provide you with an operating system. This is also equivalent to using $Config{'osname'} (see Config for more details). Special Note for Windows Systems:

On Windows platforms, $^O does not help much: since it is always MSWin32, it does not talk about the difference between 95/98 / ME / NT / 2000 / XP / CE / .NET. Use Win32::GetOSName() or Win32::GetOSVersion() (see Win32 and perlport ) to distinguish between options.

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

+5
source

To determine which OS your script is on, you can use $^O

 print $^O 

and Linux :: Distribution to check the distribution:

 use Linux::Distribution qw(distribution_name distribution_version); my $linux = Linux::Distribution->new; if (my $distro = $linux->distribution_name()) { my $version = $linux->distribution_version(); print "you are running $distro, version $version\n"; } else { print "distribution unknown\n"; } 
+1
source

All Articles