-2

我有一个简短的 bash 脚本,可以在 /etc/os-release 中找到发布 ID,并根据该结果打印一个字符串。如果可能,我想将其转换为 perl。我会很感激这方面的任何帮助。

这是我正在使用的脚本:

#!/bin/bash

grep "ID=fedora" /etc/os-release > /dev/null 2>&1
if [ $? = 0 ]; then
echo "You are running Fedora"
else
echo "You are running Ubuntu"
fi

谢谢,祝你有美好的一天。:) 帕特里克。

4

6 回答 6

1
#!/usr/bin/perl
use strict;
use warnings;

# Open /etc/os-release and read lines into array @list
open(F,'/etc/os-release');
my @list=<F>;
close F;

# Search for all lines containing "ID=fedora"
my @matchinglines= grep /ID=fedora/,@list;

# If the number of matching lines is >0 it's Fedora
if(scalar @matchinglines>0){
    print "You are running Fedora\n";
} else {
    print "You are running Ubuntu\n";
}
于 2013-10-01T22:04:21.230 回答
1
perl -lne'
  last if $f = /ID=fedora/;
  END{ print "You are running ", $f ? "Fedora":"Ubuntu" }
' /etc/os-release
于 2013-10-02T11:54:39.157 回答
1

不知道为什么要将它转换为 Perl。Shell 脚本是满足此类要求的最佳方式。

以下perl脚本是一种转换方式

#!/usr/bin/perl
use warnings;
use strict;

my $fedora = 0;
open my $fread "<", "/etc/os-release" or die $!;
while (<$fread>) {
    if (/ID=fedora/) {
        $fedora = 1;
        last;
    }
}
if ($fedora) {
    print "You are running Fedora\n";
} else {
    print "You are running Ubuntu\n";
}
close $fread;
于 2013-10-01T22:02:37.940 回答
0

作为一个经验丰富的神风敢死队:

#!/bin/bash

ID="something unknown"
test -r /etc/os-release && . /etc/os-release
echo You are running "$ID"
于 2013-10-03T06:51:58.680 回答
0
perl -ne 'print "You are running $1\n" if /^ID=(.+)/' /etc/os-release
于 2013-10-01T22:12:18.533 回答
0

一种方法,虽然不是最有效的,因为它读取内存中的整个文件:

perl -MList::Util=first -e '
    printf qq|You are running %s\n|, 
        ( first { m/ID=fedora/ } <> ) ? 
            q|Fedora| 
                : 
            q|Ubuntu|
' /etc/os-release
于 2013-10-01T21:44:53.120 回答