Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect console output to a text file

I am executing a Perl program. Whatever is being printed on my console, I want to redirect that to a text file.

like image 518
Cindrella Avatar asked May 21 '12 08:05

Cindrella


4 Answers

The preferred method for this is to handle redirection via the command line, e.g.

perl -w my_program.pl > my_output.txt

If you want to also include stderr output then you can do this (assuming your shell is bash):

perl -w my_program.pl &> my_output.txt
like image 133
Paul R Avatar answered Oct 26 '22 12:10

Paul R


If you want your output to be printed on console as well as logs then append this line to you code (e.g. before any print statements)

open (STDOUT, "| tee -ai logs.txt");
print "It Works!";

After last print in your script

close (STDOUT);

For error messages only,

open (STDERR, "| tee -ai errorlogs.txt");
like image 37
MayurKubavat Avatar answered Oct 26 '22 14:10

MayurKubavat


In the CLI you can use >, like this:

perl <args> script_name.pl > path_to_your_file

If you want to do this inside the perl script, add this code before you print anything:

open(FH, '>', 'path_to_your_file') or die "cannot open file";
select FH;
# ...
# ... everything you print should be redirected to your file
# ...
close FH;  # in the end
like image 35
ArtMat Avatar answered Oct 26 '22 14:10

ArtMat


On Unix, to capture everything that goes to your terminal, you want to redirect both the standard output and the standard error.

With bash, the command resembles

$ ./my-perl-program arg1 arg2 argn > output.txt 2>&1

The C shell, csh derivatives such as tcsh, and newer versions of bash understand

$ ./my-perl-program arg1 arg2 argn >& output.txt

to mean the same thing.

The syntax for the command shell on Windows resembles Bourne shell's.

C:\> my-perl-program.pl args 1> output.txt 2>&1

To set up this redirection in your Perl code, add

open STDOUT, ">", "output.txt" or die "$0: open: $!";
open STDERR, ">&STDOUT"        or die "$0: dup: $!";

to the beginning of your program’s executable statements.

like image 42
Greg Bacon Avatar answered Oct 26 '22 13:10

Greg Bacon