perl脚本中运行含有管道的系统命令时,不能将错误输出重定向到文本

bu110 2012-10-08 04:16:41
我有一段perl脚本如下:
while(1)
{
my @i = ();
my $command = <FH>;
if(not defined ($command))
{
last;
}
chomp($command);
print RESULT "$command\n";
@i = `$command 2>&1`;
print RESULT @i;
}
FH和RESULT 都是文件句柄,
结果文件:
cat /etc/opasswd1
cat: /etc/opasswd1: No such file or directory
cat /etc/opasswd1 | grep -v "^#"

好像命令行中不加管道就能将标准输出打印到文本中,加了管道就不能输出到文本中,但是会打到屏幕上,
请高手帮忙看下,谢谢!

...全文
189 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
bu110 2012-10-09
  • 打赏
  • 举报
回复
自己搞定,添加代码如下:
open (RESULT,">$r_file");
open STDERR, ">&RESULT";
while(1)
{
my @i = ();
my $command = <FH>;
if(not defined ($command))
{
last;
}
chomp($command);
print RESULT "$command\n";
@i = `$command 2>&1`;
print RESULT @i;
}
close STDERR;
close RESULT;
bu110 2012-10-09
  • 打赏
  • 举报
回复
感谢楼上的回答,但是还是没有解决我的问题!
bugs2k 2012-10-08
  • 打赏
  • 举报
回复
Because backticks do not affect standard error, use shell file descriptor syntax (assuming the shell supports this) if you care to address this. To capture a command's STDERR and STDOUT together:

$output = `cmd 2>&1`;

To capture a command's STDOUT but discard its STDERR:

$output = `cmd 2>/dev/null`;

To capture a command's STDERR but discard its STDOUT (ordering is important here):

$output = `cmd 2>&1 1>/dev/null`;

To exchange a command's STDOUT and STDERR in order to capture the STDERR but leave its STDOUT to come out the old STDERR:

$output = `cmd 3>&1 1>&2 2>&3 3>&-`;
bu110 2012-10-08
  • 打赏
  • 举报
回复
当命令中文件存在的时候,能正确输出到文本,如下:
cat /etc/pam.d/su | grep -v "^#"
auth sufficient pam_rootok.so
auth sufficient pam_wheel.so trust use_uid

37,701

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧