2012-03-20 27 views
-4

在下面的命令,我想wrtie输出到一个文件,也输出变量得到STDOUT,STDERR沿着我怎么能做到这一点的perl得到输出中的文件,STDERR和STDOUT

 my($output) = `ssh login.com ls /tmp > filename 2>&1`; 
     print "\n=========$output============"; 

+0

看一看这个答案:http://stackoverflow.com/a/9784064/1137055 – dgw 2012-03-20 09:57:35

回答

0

一旦完成该文件,就会捕获该文件。

my ($output) = `ssh login.com ls /tmp/ > filename 2>&1;cat filename` 
print "\n=========$output============"; 

编辑:如果保持退出代码是很重要的(我认为在https://stackoverflow.com/a/9784064/1137055的答案都比较齐全,少哈克):

`ssh login.com ls /tmp/ > filename 2>&1`; # run command and output to a file 
my $code = $?; 
my $output = { local $/ = undef; open FILE, "file" or die "Couldn't open file: $!"; $string = <FILE>; close FILE; } # "slurp" the file in using perl 
print "\n=========$output============$code========\n"; 

或更少的理想的解决方案:

`ssh login.com ls /tmp/ > filename 2>&1`; # run command and output to a file 
my $code = $?; 
my $output = `cat filename` # read the file by shell 
print "\n=========$output============$code========\n"; 
+0

的是什么猫文件名???????? – Rajeev 2012-03-20 09:46:33

+0

>将输出重定向到“文件名”,; seperates命令,“猫文件名”将输出新保存的文件到标准输出 – 2012-03-20 09:48:15

+0

但我relasied,在这种情况下,我们没有得到一个确切的返回值,例如:我的($输出)='ssh login.com ls/tmp11/> filename 2>&1; cat filename'返回状态将为0仍然有noo目录为/ tmp11 – Rajeev 2012-03-20 09:54:23

0

您应该使用CPAN的SSH :: *模块之一来执行此操作。或者你可以使用“tee”shell命令。

my $output = `ssh login.com ls /tmp/ 2>&1 | tee filename` 
2

捕获结果并让Perl将其打印到文件中更明显吗?

use strict; 
use warnings; 

use Capture::Tiny qw/capture_merged/; 

open my $log, '>', 'filename'; 

$|++; #no buffering 
my ($result, $status) = capture_merged { system 'ssh login.com ls /tmp' }; 

print "Result: $result"; 
print $log $result; 
+0

,因为我相信这是真的,所以我认为这个问题只是OP的一个骗局一个小时前的问题。 – 2012-03-20 13:28:50

相关问题