Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect stdout and stderr from inside a batch file

Tags:

Is there a way to redirect stdout and stderr for a batch file from inside it.

I'm imagining something like

set STDOUT=stdout.log echo Some text a.exe b.exe c.exe 

Where both Some text, and the output of a.exe, b.exe and c.exe would go to stdout.log

Is this possible?

like image 857
sashoalm Avatar asked Nov 15 '12 14:11

sashoalm


People also ask

How do I redirect stdout and stderr to the same file?

Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator. We have created a file named “sample.

How would you redirect a command stderr to stdout?

The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.

How do I redirect both standard and standard error on the same location?

Discussion. &> or >& is a shortcut that simply sends both STDOUT and STDERR to the same place—exactly what we want to do.


2 Answers

It is more efficient to redirect once for the entire collection of commands than it is to redirect (with append) each individual command. It takes time to intialize the redirection. It may not be noticable for a few redirected commands, but if done in a loop with many iterations, it can become quite significant.

One method is to enclose the entire block of redirected commands within parentheses and redirect outside the parentheses

>stdout.log 2>&1 (   echo Some text   a.exe   b.exe   c.exe ) 

Another option is to put your commands in a subroutine and redirect the CALL

call :redirect >stdout.log 2>&1 exit /b  :redirect echo Some text a.exe b.exe c.exe exit /b 
like image 146
dbenham Avatar answered Oct 18 '22 09:10

dbenham


Yes, you need to redirect and append stdout to your file (1>> %STDOUT%) and connect stderr to stdout (2>&1):

set STDOUT=stdout.log echo Some text 1>> %STDOUT% 2>&1 a.exe 1>> %STDOUT% 2>&1 b.exe 1>> %STDOUT% 2>&1 c.exe 1>> %STDOUT% 2>&1 

@EitanT correctly noted that your question doesn't necessarily imply writing both stderr and stdout into the same file. So for completeness, here's a version writing into separated files:

set STDOUT=stdout.log set STDERR=stderr.log echo Some text 1>> %STDOUT% 2>> %STDERR% a.exe 1>> %STDOUT% 2>> %STDERR% b.exe 1>> %STDOUT% 2>> %STDERR% c.exe 1>> %STDOUT% 2>> %STDERR% 
like image 29
zb226 Avatar answered Oct 18 '22 08:10

zb226