Perl 代码实现:
#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;
open(LOG, '>', 'LOG_FILE') or die "Can't redirect stdout: $!";
open(CMD, 'ls |');
open(STDERR, '>&', STDOUT) or die "Can't redirect stderr: $!";
open(STDERR, '>', 'LOG_FILE') or die "Can't redirect stderr: $!";
print "LOG_FILE\n";
while (<CMD>) {
&lprint ($_)
}
sub lprint {
my ($line) = @_;
print LOG $line;
print $line;
}
close(CMD) or die "close CMD failed: $!";
exit(1);
利用Perl的Tee模块:
#!/usr/bin/perl
use IO::Tee;
$tee = IO::Tee->new(">> log.txt", \*STDOUT);
print $tee "Log on ".scalar(localtime)."\n";
或
#!/usr/bin/perl
open (STDOUT, "| tee -ai log.txt");
print "Log on ".scalar(localtime)."\n";
close (STDOUT);