Search code examples
perlunixstdoutcsh

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.


Solution

  • 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.