perl脚本中运行含有管道的系统命令时,不能将异常输出重定向到文本
perl脚本中运行含有管道的系统命令时,不能将错误输出重定向到文本
我有一段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 "^#"
好像命令行中不加管道就能将标准输出打印到文本中,加了管道就不能输出到文本中,但是会打到屏幕上,
请高手帮忙看下,谢谢!
------解决方案--------------------
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>&-`;
我有一段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 "^#"
好像命令行中不加管道就能将标准输出打印到文本中,加了管道就不能输出到文本中,但是会打到屏幕上,
请高手帮忙看下,谢谢!
------解决方案--------------------
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>&-`;