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?
How would I do this?
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;
}
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. UseWin32::GetOSName()
orWin32::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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With