简体   繁体   中英

Perl script redirect stderr and stdout to a file

I'm having trouble doing this. My script prints messages to stout and stderr, and I want them all to be directed to a file that I can view at my leisure later.

Here is what I tried:

$location/myscript.pl -arg1 $var1 -arg2 $var2 -verbose 1 &>myscript.log

So my script has a few arguments that I need to set, then I try &>myscript.log to create this log file and redirect there. However I get "Invalid null command" and when I press up on the key pad it shows the command I tried executing as:

$location/myscript.pl -arg1 $var1 -arg2 $var2 -verbose 1 & > myscript.log

I think my syntax is wrong or something.

Thanks.

script.pl ... >myscript.log 2>&1
  • >myscript.log opens the file for writing and uses that handle for STDOUT.
  • 2>&1 makes STDERR the same handle as STDOUT.

Order matters.


For csh , the simplest way is:

sh -c 'script.pl ... >myscript.log 2>&1'

Ok, I'm just kidding :) You can actually do

script.pl ... >& file

csh 's redirection support is far more limited than that of sh and its derivatives, but this is something it can do.

This code doesn't follow your approach, but it could be useful for you as well. You could enable it via one of your agruments inside your script.

#===
# x.pl
#===
use IO::Handle;
open(STDOUT_AND_ERR_LOG, ">stdout_and_err.log") or die;

# ensure all writes are immediately flushed STDOUT_AND_ERR_LOG->autoflush(1);

# redirect both stdout and err to the log *STDERR = *STDOUT = *STDOUT_AND_ERR_LOG;

# now try it
print "Hello stdout!\n";
print STDERR "Hello stderr!\n";
#=== EOF

Credits to ActiveState.com

As mentioned by ikegami , bash solution is:

script.pl ... >myscript.log 2>&1

On my FreeBSD box with csh solution is:

script.pl ... >& myscript.log

Try this:

$location/myscript.pl -arg1 $var1 -arg2 $var2 -verbose 1 1>myscript.stdout 2>myscript.stderr

This will redirect the output and error to two separate files. To do it in the same file (this means redirect stderr and append it to stdout):

$location/myscript.pl -arg1 $var1 -arg2 $var2 -verbose 1 > myscript.log 2>&1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM