Reputation: 349
I'm trying to test if a backtick output string (it is a string, right?) contains a substring.
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";
But, this isn't working. It never enters the if
statement.
The backtick output:
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
Clearly the substring is in the first line. Why won't it recognize this?
Upvotes: 2
Views: 911
Reputation: 386541
tar
, like most programs, writes error messages to STDERR. That's the purpose of STDERR.
Backticks only capture STDOUT.
You could redirect tar
's STDERR to its STDOUT, but why not just check its exit code.
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;
Advantages:
tar
finishes before being sent to the screen.shell_quote
.Upvotes: 1
Reputation: 62236
Check if backticks produced an error with $?
:
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
Upvotes: 0