[英]perl system command redirection to log files
我试图将perl系统命令重定向到输出文件,以及下面的代码和时间,但它不工作?
$cmd="echo hi";
($second, $minute, $hour) = localtime();
$time="$hour:$minute:$second";
system("$time>new.txt");
system("$cmd 1>>new.txt 2>>&1");
如果要将变量$time
写入文本文件,请open
可写文件句柄并将其打印到文件中。
open(my $outfile, '>', 'new.txt');
print $outfile $time;
...
其次,您的输出重定向应为:
1>>new.txt 2>&1
这意味着“将STDOUT(1)附加到new.txt,将STDERR(2)重定向到STDOUT(1)”。 >>
对第二部分毫无意义。
最后,我(以及其他所有perl程序员)强烈建议在脚本中使用strict
和warnings
pragma。 这将帮助您了解脚本中的任何错误或潜在问题。 一旦你完成了这个,所有变量都必须用my
声明,这是一个很好的习惯。 毕竟,你的脚本应该是这样的:
# recommended pragmas:
use strict;
use warnings;
# declare all new variables with "my"
my $cmd="echo hi";
my ($second, $minute, $hour) = localtime();
my $time="$hour:$minute:$second";
# open a writeable filehandle and print to the filehandle
open(my $outfile, '>', 'new.txt');
print $outfile $time,"\n"; # I've added a newline character here so that
# the time and the command's output are on different lines ;)
system("$cmd 1>>new.txt 2>&1");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.