2017-04-12 86 views
-3

我是Perl新手,Perl:意外令牌附近的语法错误`|'

我打算从keytool使用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 "[email protected]"; 
      } 
     } 
    } 

但密钥存储指令工作,为grep的一部分收到错误为:

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

请建议什么错在此示例代码

+2

的错误不是在Perl,它从壳牌公司(见错误消息的开头'sh')。可能你的'$ finali'变量没有被定义,或者是空字符串。 – Robert

+0

对不起。纠正 – user092

回答

2

@test包含NEWLINE-终止的项目。这会导致| 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]的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 "[email protected]"; 
} 
+0

编辑的代码示例请检查 – user092

+0

尝试用“\ n”但仍然得到相同的问题 – user092

+0

我试过chomp(@test)但仍然得到这个sh:-c:第1行:语法错误附近的意外令牌' “ sh:-c:第1行:'| grep有效' – user092

相关问题