简体   繁体   中英

Perl script to capture stderr and stdout of command executed in back-quotes

In the following command which I execute in a Perl script, how do I capture stderr?

my $output = `ssh login.com git clone --bare user@login.com:/nfs/repo/ /nfs/repo//4124/`;
if ($? ne '0')
{ 
    $stderr = $output;
    print $stderr;
}
else
{
    $stdout = $output;
    print $stdout;
}

您可以使用Capture :: Tiny捕获stdout,stderr或两者合并。

my $output = `ssh login.com git clone --bare user@login.com:/nfs/repo/ /nfs/repo//4124/ 2>&1`;

最后的2>&1将标准错误发送到与标准输出相同的位置,该错误由反引号捕获。

I'm personally a fan of the core module IPC::Open3 , though the answer with 2>&1 will get both stderr and stdout in the same stream (and usually good enough). The following will keep them separated. There are less low level solutions though.

use IPC::Open3
my $pid = open3(\*CHLD_IN, \*CHLD_OUT, \*CHLD_ERR, qw(ssh login.com git clone --bare user@login.com:/nfs/repo/ /nfs/repo//4124/));

waitpid( $pid, 0 );
my $child_exit_status = $? >> 8;
if (child_exit_status != 0)
{
    my $stderr = do { local $/; <CHLD_ERR> };
    print "Failed command because: $stderr\n";
}
my $stderr = do { local $/; <CHLD_OUT> };
print "command stdout: $stdout\n";
use IPC::Run;
my $rcode = run [ "ssh", "login.com", "git", ... ],
    undef, \my $stdout, \my $stderr;

if ($rcode) {
  print $stderr, "\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM