JDS
JDS

Reputation: 16978

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.

Upvotes: 0

Views: 6263

Answers (4)

ikegami
ikegami

Reputation: 385789

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.

Upvotes: 2

Galimov Albert
Galimov Albert

Reputation: 7357

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

Upvotes: 2

capfan
capfan

Reputation: 827

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

Upvotes: 2

asf107
asf107

Reputation: 1146

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

Upvotes: 1

Related Questions