Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to capture output from system command to a text file?

I’m trying to capture output from using Perl’s system function to execute and redirect a system command’s ouptut to a file, but for some reason I’m not getting the whole output.

I’m using the following method:

system("example.exe >output.txt");

What’s wrong with this code, or is there an alternative way of doing the same thing?

like image 686
int80h Avatar asked Oct 17 '11 20:10

int80h


People also ask

How do I print the output of a command in a text file?

Any command that has a command window output (no matter how big or small) can be appended with > filename. txt and the output will be saved to the specified text file.

How do I copy a command output to a file?

the shortcut is Ctrl + Shift + S ; it allows the output to be saved as a text file, or as HTML including colors!

How do you save the output of a command in a text file in Linux?

Method 1: Use redirection to save command output to file in Linux. You can use redirection in Linux for this purpose. With redirection operator, instead of showing the output on the screen, it goes to the provided file. The > redirects the command output to a file replacing any existing content on the file.

How do I pipe a PowerShell output to a text file?

To send a PowerShell command's output to the Out-File cmdlet, use the pipeline. Alternatively, you can store data in a variable and use the InputObject parameter to pass data to the Out-File cmdlet. Out-File saves data to a file but it does not produce any output objects to the pipeline.


1 Answers

Same as MVS's answer, but modern and safe.

use strict;
use warnings;

open (my $file, '>', 'output.txt') or die "Could not open file: $!";
my $output = `example.exe`; 
die "$!" if $?; 
print $file $output;

easier

use strict;
use warnings;

use autodie;

open (my $file, '>', 'output.txt');
print $file `example.exe`;

if you need both STDOUT and STDERR

use strict;
use warnings;

use autodie;
use Capture::Tiny 'capture_merged';

open (my $file, '>', 'output.txt');
print $file capture_merged { system('example.exe') };
like image 171
Joel Berger Avatar answered Oct 13 '22 15:10

Joel Berger