Need to output the action of a system() command and have a progress indicator
-
29-10-2019 - |
Question
I have a nice progress indicator from Need a progress indicator for a Perl system() command using T:R:G mod
open(my $cmd, '-|', "$command $flags_args 2>/dev/null")
or print "\nAttention: Command $command $flags_args failed $!"
and return 1;
while (<$cmd>)
{
$percentage = ($cntr/$lines) * 100;
$percentage = 100 if $percentage > 100;
printf("Progress: %3d%%\r", $percentage);
$cntr++;
}
close($cmd);
Now my I want logging of the STDOUT and STDERR of the commands output. I'm not too familiar with pipe output so I tried adding:
print $LOG $cmd
and
print $LOG Dumper(\$cmd)
before the end of the while loop. It did not work. The first output
GLOB(0x11df7a0)GLOB(0x11df7a0)GLOB(0x11df7a0)
the second
$VAR1 = \\*{'::$cmd'};
$VAR1 = \\*{'::$cmd'};
$VAR1 = \\*{'::$cmd'};
Does anyone know how I can get the output from the piped $cmd? Example for a $command = make command
Making all in src
make[1]: Entering directory `/tmp'
Making all in include
make[2]: Entering directory '/tmp/2'
...
Solution
Try making it
print $LOG $_;
or maybe just
print $LOG;
(since $_
is the default if nothing is specified)
To explain: $cmd
is the file you're reading from; $_
is the line read from it. You can make it clearer by writing:
while ($line = <$cmd>) {
print $LOG $line;
...
}
OTHER TIPS
$cmd
is the I/O handle to your command's output, an internal data type that doesn't make much sense to print. You want to use <$cmd>
or readline($cmd)
to get the output of it, which you already do in your while
loop:
while (<$cmd>) # same as: while (defined($_ = readline($cmd)))
{
# last line from command is now stored in $_
print $LOG $_;
$percentage = ($cntr/$lines) * 100;
$percentage = 100 if $percentage > 100;
printf("Progress: %3d%%\r", $percentage);
$cntr++;
}