我正在尝试测试反引号输出字符串(它是一个字符串,对吧?)是否包含一个子字符串。
my $failedCoutner = 0;
my $tarOutput = `tar -tvzf $tgzFile`;
print "$tarOutput\n";
my $subStr = "Cannot open: No such file or directory";
if (index($tarOutput, $subStr) != -1)
{
push(@failedFiles, $tgzFile);
$failedCounter++;
print "Number of Failed Files: $failedCounter\n\n\n";
}
print "Number of Failed Files: $failedCounter\n\n\n";
但这不起作用。它永远不会进入if语句。
反引号输出:
tar (child): /backup/Arcsight/EDSSIM004: Cannot open: No such file or directory
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now
Number of Failed Files: 0
显然,子串位于第一行。为什么不认识这个?
答案 0 :(得分:1)
tar
将错误消息写入STDERR。这就是STDERR的目的。
反引号仅捕获STDOUT。
您可以将tar
的STDERR重定向到其STDOUT,但为什么不检查其退出代码。
system('tar', '-tvzf', $tgzFile);
die "Can't launch tar: $!\n" if $? == -1;
die "tar killed by signal ".($? & 0x7F) if $? & 0x7F;
die "tar exited with error ".($? >> 8) if $? >> 8;
优点:
tar
完成后才会保留输出。shell_quote
。答案 1 :(得分:0)
检查$?
是否backticks产生了错误:
use warnings;
use strict;
my $tarOutput = `tar -tvzf doesnt_exist.tar.gz`;
if ($?) {
print "ERROR ... ERROR ... ERROR\n";
}
else {
# do something else
}
__END__
tar (child): doesnt_exist.tar.gz: Cannot open: No such file or directory
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now
ERROR ... ERROR ... ERROR