Read console output of a shell script in Perl
Let's say I've got a shell script called print_error.sh
looking like this:
#!/usr/bin/bash
echo "ERROR: Bla bla, yada yada."
exit 1
Now I'm in a Perl 开发者_如何转开发script, calling this shell script with
system("print_error.sh")
I now want to read the console output of print_error.sh
and write it to a Log4perl logger.
How can I achieve this?
Either use backticks:
my $results = `print_error.sh`;
or see open:
http://perldoc.perl.org/functions/open.html
Here's the solution I've found:
#!/usr/bin/perl
use Log::Log4perl;
my $logfile = "log.txt";
$ENV{"LOGFILE"} = $logfile;
Log::Log4perl->init("log4perl.properties");
$logger = Log::Log4perl->get_logger();
$logger->info("pos 1");
system("./print_error.sh 0 2>&1 >> $logfile") == 0
or die "perl error";
$logger->info("pos 2");
exit 0
See also here.
精彩评论