繁体   English   中英

如何使用Perl快速检查是否安装了Linux`unzip`?

[英]How can I quickly check if Linux `unzip` is installed using Perl?

如何快速检查是否使用Perl安装Linux unzip

跑吧。

认真。

据推测, 为什么你想知道如果安装它的原因,是因为你以后需要运行它。 在这种情况下,还不足以知道它是否已安装 - 无论如何 - 您还需要知道它是否可执行,是否在路径中,脚本运行的用户ID是否具有运行所需的权限它,等等。 您只需运行即可查看所有内容。

`which unzip`

如果有输出,则指向解压缩的位置。 如果没有输出,则不会显示任何内容。 这依赖于解压缩你的道路。

这将验证unzip命令是否在您的路径上以及当前用户是否可执行。

print "unzip installed" if grep { -x "$_/unzip"}split /:/,$ENV{PATH}

取自Module :: Install :: Can:

sub can_run {
  my ($self, $cmd) = @_;

  my $_cmd = $cmd;
  return $_cmd if (-x $_cmd or $_cmd = MM->maybe_command($_cmd));

  for my $dir ((split /$Config::Config{path_sep}/, $ENV{PATH}), '.') {
    next if $dir eq '';
    my $abs = File::Spec->catfile($dir, $_[1]);
    return $abs if (-x $abs or $abs = MM->maybe_command($abs));
  }

  return;
}

然后:

my $is_it_there = can_run("unzip");

我只是使用Archive :: Extract并将其配置为更喜欢二进制文件到Perl模块。 如果unzip ,它会使用它。 否则,它会回归纯粹的Perl。

perl -e 'if (-e "/usr/bin/unzip") { print "present\n"; } else { print "not present\n"; }'

任何特定的unzip 我使用的Linux系统有Info-Zip的unzip ,如果你要检查它,你可以这样做

if ( (`unzip`)[0] =~ /^UnZip/ ) {
# ...
}

如果你想让它更安全一点,你会做:

#!/usr/bin/perl -T

use strict; use warnings;

$ENV{PATH} = '/bin:/usr/bin:/usr/local/bin';

use File::Spec::Functions qw( catfile path );

my @unzip_paths;

for my $dir ( path ) {
    my $fn = catfile $dir, 'unzip';
    push @unzip_paths, $fn if -e $fn;
}

if ( @unzip_paths > 1 ) {
    # further narrow down by version etc
}

另请参阅我的多个脚本

也许你应该退一步问为什么你需要Perl的unzip命令。 是因为你想要解压缩一些东西吗? 如果是这样,那么你应该考虑使用众多可用模块之一进行编程,例如Archive :: Zip

为什么要在使用Perl时调用系统命令? 使用解压缩模块,例如Archive :: Extract ,(或CPAN中的其他模块)

你可以尝试这个脚本(测试)。 它利用了which命令。

#!/usr/bin/perl -w

use strict;

my $bin = "unzip";
my $search = `which $bin 2>&1`;
chomp($search);
if ($search =~ /^which: no/)
{
    print "Could not locate '" . $bin . "'\n";
    exit(1);
} else {
    print "Found " . $bin . " in " . $search . "\n";
    exit(0);
}

干杯,

布拉德

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM