Perl:意外标记附近的语法错误`|'

时间:2017-04-12 16:03:52

标签: perl unix sh keystore keytool

我是perl的新手,

我想使用keytool从密钥库中获取有效日期。

示例代码:

my @test = `cd /usr/keystores; find . -name '\*\_old\_id\.jks'`;
print "@test";

my @fus_res=();

s/\.\///g for @test;
print "@test";


foreach $res(@test)
{
 my $short =substr($res,0,-14);

 push(@fus_res,$short);
}


    foreach my $j(0 ..$#fus_res) {
        foreach my $i(0 .. $#test) {
            if ($i eq  $j) {
                my $finali="$test[$i]";
                my $finalj="$fus_res[$j]";
                my @test1=`cd /usr/keystores;keytool -list -v -storepass "2xxpw" -alias $finalj -keystore $finali | grep Valid `;
                print "test_final=@test1";
            }
        }
    }

但是keystore命令正在运行,因为grep部分获取错误:

sh: -c: line 1: syntax error near unexpected token `|'
sh: -c: line 1: ` |grep Valid '

请提示此示例代码中的错误

1 个答案:

答案 0 :(得分:2)

@test包含换行符已终止的项目。这导致| grep Valid作为单独的(无效)命令执行。

更改

my @test = `cd /usr/keystores; find . -name '\*\_old\_id\.jks'`;

my @test = `cd /usr/keystores; find . -name '*_old_id.jks'`;
chomp(@test);

并替换两者

print "@test";

print "$_\n" for @test;

注意:

  • 如果您的文件名包含特殊字符,则会出现(其他)问题。 [String :: ShellQuote]' s shell_quote应该用于将文本插入shell命令。
  • s/\.\///g for @test;应为s/^\.\/// for @test;。您只想删除前导./
  • foreach my $j(0 ..$#fus_res) { foreach my $i(0 .. $#test) { ... } }应该只是foreach my $j(0 ..$#fus_res) { my $i = $j; ... } !!!

更好的版本:

use strict;
use warnings qw( all );
use feature qw( say );

use File::Find::Rule   qw( );
use String::ShellQuote qw( shell_quote );

my @qfns =
   Find::File::Rule
      ->relative
      ->name('*_old_id.jks')
      ->file
      ->in('/usr/keystores');

say for @qfns;

for my $qfn (@qfns) {
     my $finali = $qfn;
     my $finalj = substr($qfn, 0, -14);

     my $cmd = shell_quote("keytool", "-list", "-v", "-storepass", "2xxpw", "-alias", "$finalj", "-keystore", "$finali");

     my @output = grep { /Valid/ } `cd /usr/keystores ; $cmd`;
     # ...Error checking...

     print "test_final=@output";
}