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

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


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') };


Redirecting the output with plain > will only catch STDOUT. If you also want to catch STDERR, use 2>&1:

perl -e 'system("dir blablubblelel.txt >out.txt 2>&1");' 

For more details, see Perlmonks


When you want recirect output permanently, you can do:

#redirect STDOUT before calling other functionsopen STDOUT,'>','outputfile.txt' or die "can't open output";system('ls;df -h;echo something');  #all will be redirected.